Home > Java > javaTutorial > body text

Detailed explanation of scanning multimedia files in Android

高洛峰
Release: 2017-01-16 17:26:20
Original
1634 people have browsed it

This article analyzes the system source code and tells how to add multimedia files created by the program to the system's media library, how to delete them from the media library, and the problems that most program developers often encounter when they are unable to add to the media library. . I will explain these issues one by one through analysis of the source code.

Multimedia file scanning mechanism in Android

Android provides a great program to handle adding multimedia files to the media library. This program is MediaProvider. Now let's briefly look at the following program. First, take a look at its Receiver

    <receiver android:name="MediaScannerReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.MEDIA_MOUNTED" />
            <data android:scheme="file" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.MEDIA_UNMOUNTED" />
            <data android:scheme="file" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.MEDIA_SCANNER_SCAN_FILE" />
            <data android:scheme="file" />
        </intent-filter>
    </receiver>
Copy after login

MediaScannerReceiver only receives the correct intent that conforms to the action and data rules.

How MediaScannerReciever handles Intent

1. Scan internal storage (non-built-in and external sdcard) if and only if action android.intent.action.BOOT_COMPLETED is received
2. Except Intents other than the action android.intent.action.BOOT_COMPLETED must have data passed on.
3. When receiving the Intent.ACTION_MEDIA_MOUNTED intent, scan the Sdcard
4. When receiving the Intent.ACTION_MEDIA_SCANNER_SCAN_FILE intent, there is no problem in the detection and a single file will be scanned.

How MediaScannerService works

In fact, MediaScannerReceiver does not really handle the scanning work, it starts a service called MediaScannerService. Let's continue looking at the service part of MediaProvider's manifest.

 <service android:name="MediaScannerService" android:exported="true">
        <intent-filter>
            <action android:name="android.media.IMediaScannerService" />
        </intent-filter>
    </service>
Copy after login

scanFile method in MediaScannerService

private Uri scanFile(String path, String mimeType) {
    String volumeName = MediaProvider.EXTERNAL_VOLUME;
    openDatabase(volumeName);
    MediaScanner scanner = createMediaScanner();
    return scanner.scanSingleFile(path, volumeName, mimeType);
}
Copy after login

scan method in MediaScannerService

private void scan(String[] directories, String volumeName) {
    // don&#39;t sleep while scanning
    mWakeLock.acquire();
    ContentValues values = new ContentValues();
    values.put(MediaStore.MEDIA_SCANNER_VOLUME, volumeName);
    Uri scanUri = getContentResolver().insert(MediaStore.getMediaScannerUri(), values);
    Uri uri = Uri.parse("file://" + directories[0]);
    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_STARTED, uri));
    try {
        if (volumeName.equals(MediaProvider.EXTERNAL_VOLUME)) {
            openDatabase(volumeName);
        }
        MediaScanner scanner = createMediaScanner();
        scanner.scanDirectories(directories, volumeName);
    } catch (Exception e) {
        Log.e(TAG, "exception in MediaScanner.scan()", e);
    }
    getContentResolver().delete(scanUri, null, null);
    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_FINISHED, uri));
    mWakeLock.release();
}
Copy after login

createMediaScanner method in MediaScannerService

private MediaScanner createMediaScanner() {
        MediaScanner scanner = new MediaScanner(this);
        Locale locale = getResources().getConfiguration().locale;
        if (locale != null) {
            String language = locale.getLanguage();
            String country = locale.getCountry();
            String localeString = null;
            if (language != null) {
                if (country != null) {
                    scanner.setLocale(language + "_" + country);
                } else {
                    scanner.setLocale(language);
                }
            }
        }
        return scanner;
}
Copy after login

How to scan a newly created file

Here are two ways to add newly created files to the media library.

The simplest way

Just send a correct intent broadcast to MediaScannerReceiver.

String saveAs = "Your_Created_File_Path"
Uri contentUri = Uri.fromFile(new File(saveAs));
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,contentUri);
getContext().sendBroadcast(mediaScanIntent);
Copy after login

The above minimalist method works normally in most cases, but it will not work in some cases, which will be introduced in a later section. Even if you succeed using the above method, it is recommended that you continue reading the later section on why broadcasting fails.

Using MediaScannerConnection

public void mediaScan(File file) {
    MediaScannerConnection.scanFile(getActivity(),
            new String[] { file.getAbsolutePath() }, null,
            new OnScanCompletedListener() {
                @Override
                public void onScanCompleted(String path, Uri uri) {
                    Log.v("MediaScanWork", "file " + path
                            + " was scanned seccessfully: " + uri);
                }
            });
}
Copy after login

The scanFile method of MediaScannerConnection was introduced starting from 2.2 (API 8).

Create a MediaScannerConnection object and then call the scanFile method

It’s very simple, refer to http://developer.android.com/reference/android/media/MediaScannerConnection.html

How to Scan multiple files

1. Send multiple Intent.ACTION_MEDIA_SCANNER_SCAN_FILE broadcasts
2. Use MediaScannerConnection and pass in the array of paths to be added.

Why sending MEDIA_SCANNER_SCAN_FILE broadcast does not take effect

Regarding why it does not take effect on some devices, many people think it is due to the API, but it is not. This is actually related to the file path you passed in. Take a look at the onReceive code of the receiver Receiver.

public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    Uri uri = intent.getData();
    if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
        // scan internal storage
        scan(context, MediaProvider.INTERNAL_VOLUME);
    } else {
        if (uri.getScheme().equals("file")) {
            // handle intents related to external storage
            String path = uri.getPath();
            String externalStoragePath = Environment.getExternalStorageDirectory().getPath();
            Log.d(TAG, "action: " + action + " path: " + path);
            if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
                // scan whenever any volume is mounted
                scan(context, MediaProvider.EXTERNAL_VOLUME);
            } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) &&
                    path != null && path.startsWith(externalStoragePath + "/")) {
                scanFile(context, path);
            }
        }
    }
}
Copy after login

Everything is correct except the path passed in. Because you may have hardcoded the file path. Because there is such a judgment path.startsWith(externalStoragePath + "/"), here I will give a simple example.

final String saveAs = "/sdcard/" + System.currentTimeMillis() + "_add.png";
Uri contentUri = Uri.fromFile(new File(saveAs));
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,contentUri);
getContext().sendBroadcast(mediaScanIntent);
Uri uri = mediaScanIntent.getData();
String path = uri.getPath();
String externalStoragePath = Environment.getExternalStorageDirectory().getPath();
Log.i("LOGTAG", "Androidyue onReceive intent= " + mediaScanIntent
                        + ";path=" + path + ";externalStoragePath=" +
                        externalStoragePath);
Copy after login

Let’s take a look at the output log and analyze the reason.

LOGTAG Androidyue onReceive intent= Intent { act=android.intent.action.MEDIA_SCANNER_SCAN_FILE dat=file:///sdcard/1390136305831_add.png };path=/sdcard/1390136305831_add.png;externalStoragePath=/mnt/sdcard
Copy after login

The above output analysis shows that the broadcast and action you sent are correct, the data rules are also correct, and your file path also exists. However, the file path /sdcard/1390136305831_add.png does not start with The external storage root path starts with /mnt/sdcard/. Therefore, the scanning operation did not start, resulting in the file not being added to the media library. So, please check the path of the file.

How to remove from the multimedia library

If we delete a multimedia file, it means that we also need to delete the file from the media library.

Can you simply send a broadcast?

Can just sending a broadcast solve the problem? I wish it could, but it doesn't actually work. You can see it by looking at the following code.

// this function is used to scan a single file
public Uri scanSingleFile(String path, String volumeName, String mimeType) {
    try {
        initialize(volumeName);
        prescan(path, true);
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        // lastModified is in milliseconds on Files.
        long lastModifiedSeconds = file.lastModified() / 1000;
        // always scan the file, so we can return the content://media Uri for existing files
        return mClient.doScanFile(path, mimeType, lastModifiedSeconds, file.length(),
                false, true, MediaScanner.isNoMediaPath(path));
    } catch (RemoteException e) {
        Log.e(TAG, "RemoteException in MediaScanner.scanFile()", e);
        return null;
    }
}
Copy after login

Just like the above code, it will check whether the file exists. If the file does not exist, the downward execution will be stopped directly. So this won't work. then what should we do?

public void testDeleteFile() {
    String existingFilePath = "/mnt/sdcard/1390116362913_add.png";
    File  existingFile = new File(existingFilePath);
    existingFile.delete();
    ContentResolver resolver = getActivity().getContentResolver();
    resolver.delete(Images.Media.EXTERNAL_CONTENT_URI, Images.Media.DATA + "=?", new String[]{existingFilePath});
    
    }
Copy after login

The above code can work, just delete it directly from the MediaProvider. For specific deletion codes, please refer to Code Snippet for Media on Android

One More Thing

For more detailed explanations of multimedia file scanning operations in Android, please pay attention to the PHP Chinese website for related articles!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!