Tuesday, May 15, 2012

Android: How to Check if Media Scanner is Running?

In our application, some of the action need to be blocked while android media scanner running (For example loading existing media and listing down).

In this case, we couldn't find a direct API to check if Media Scanner is running. We could find following two options:
Option 01:
Android will broadcast Intent.ACTION_MEDIA_SCANNER_STARTEDIntent.ACTION_MEDIA_SCANNER_FINISHED in starting and finishing of scanning respectively. So we create following  BroadcastReceiver:

public class MediaScannerBroadcastReceiver extends BroadcastReceiver {
public static boolean mMedaiScanning = false;
        @Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_MEDIA_SCANNER_STARTED)){
mMedaiScanning = true;
}
if(intent.getAction().equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)){
mMedaiScanning = false;
}
}
}


And register this in manifest file:

<receiver android:name=" MediaScannerBroadcastReceiver">
     < intent-filter>

           < action android:name="android.intent.action.MEDIA_SCANNER_FINISHED" >  < /action>
          < action android:name="android.intent.action.MEDIA_SCANNER_STARTED" >  < /action>
           < data android:scheme="file" >  < /data>
      < /intent-filter>
</receiver>


Then in cases we we wanted to check the condition we sued as following:
if( MediaScannerBroadcastReceiver.mMedaiScanning){
     .....
}

But, most of the devices will run Media Scanner in boot up, in adding SDCard or mount/unmount devices to PC. In those cases our application is invoked and loaded into memory.

Option 02:
found that the media scanner service insert and delete a record into media store when starting and finishing the scanning. So we try to check the record in the media store as follows:

private boolean isMediaScannerRunning() {
Cursor query = getContentResolver().query(MediaStore.getMediaScannerUri(),
                                                   new String[]{MediaStore.MEDIA_SCANNER_VOLUME}, nullnullnull);
        if(query!=null){
         if(query.moveToFirst()){
         int columnIndex = query.getColumnIndex(MediaStore.MEDIA_SCANNER_VOLUME);
         String volumeName = query.getString(columnIndex);
         if(volumeName!=null){
         return true;
         }
         }
         query.close();
        }
        return false;
}

This option will not load the application while media scanner running. But need to consider its costly operation in query.

Lets check both options for its pros and cons.

No comments: