How to scan multimedia files in Android-java tutorial

Source: Internet
Author: User
This article describes how to scan a multimedia file in Android. This article describes how to scan a multimedia file in Android, how to scan a newly created file, and how to scan multiple files, for more information about how to add multimedia files created by programs to the system's media library and delete them from the library, and many program developers often encounter problems that cannot be added to the media library. I will analyze the source code to explain these issues one by one.

Multimedia file scanning mechanism in Android

Android provides a great program to process the media library that adds multimedia files. This program is MediaProvider. now let's take a look at the following program. First, let's take a look at its aggreger

    
         
                      
          
                          
           
          
                          
           
          
                          
           
      
 

Mediascannerpolicer only receives intents that comply with the action and data rules correctly.

How MediaScannerReciever handles Intent

1. internal storage is scanned only when action android. intent. action. BOOT_COMPLETED is received (non-built-in and external sdcard)
2. All intent except android. intent. action. BOOT_COMPLETED must have data transmission.
3. When Intent. ACTION_MEDIA_MOUNTED intent is received, scan Sdcard
4. When Intent. ACTION_MEDIA_SCANNER_SCAN_FILE intent is received, the system scans a single file.

How MediaScannerService works

In fact, MediaScannerReceiver does not actually process Scanning. it starts a service called MediaScannerService. Let's continue to look at the service section in the manifest of MediaProvider.

 
         
                      
      
 

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);}

Scan method in MediaScannerService

private void scan(String[] directories, String volumeName) {    // don'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();}

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;}

How to scan a newly created File

Here we will introduce two methods to add new files to the media library.

The simplest way

You only need to 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);

The simple method above works normally in most cases, but it does not work in some cases. I will introduce it later. Even if you use the above method successfully, we recommend that you continue to read the part about why broadcasting fails later.

Use 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);                }            });}

The scanFile method of MediaScannerConnection is introduced from 2.2 (API 8.

Create a MediaScannerConnection object and call the scanFile method.

Very simple, reference 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 to input the array of paths to be added.

Why does MEDIA_SCANNER_SCAN_FILE broadcast not take effect?

Many people think that some devices do not take effect because of the API, but they are not. this is actually related to the file path you passed in. Take a look at the onReceive code of the 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);            }        }    }}

All parts except the input path are correct. Because you may have hardcoded the file path. Because there is such a judgment path. startsWith (externalStoragePath + "/"), here is a simple small 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);

Let's take a look at the output log and analyze the cause.

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

The above output analysis shows that the broadcast and action you sent are correct, the data rules are correct, and your file path also exists. However, the file path/sdcard/1390136305831_add.png does not start with the external storage root path/mnt/sdcard. Therefore, the scan operation is not started, and the file is not added to the media library. Therefore, check the file path.

How to remove a file from a multi-media library

If we delete a multimedia file, we need to delete it from the library.

Can I simply send a broadcast?

Can sending only one broadcast solve the problem? I hope it works, but it doesn't actually work. you can see the following code.

// this function is used to scan a single filepublic 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;    }}

As with the code above, the system checks whether the file exists. if the file does not exist, it stops executing the command. So this is not acceptable. 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});        }

The above code can work and can be deleted directly from MediaProvider. For specific deletion Code, see Code Snippet for Media on Android

One More Thing

For more details about how to scan multimedia files in Android, refer to PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.