Android: Intent for when the SD card is TRULY mounted and readable
I have the following setup:
SD card Mount Receiver (MountReceiver.java)
public IntentFilter getIntentFilter() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
intentFilter.addDataScheme("file");
return intentFilter;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) {
setMounted(true);
} else if (Intent.ACTION_MEDIA_UNMOUNTED.equals(action)) {
setMounted(false);
}
}
private void setMounted(boolean isMounted) {
开发者_开发问答if (isMounted) {
doPerformQuery();
}
}
And when I register the receiver, I do:
registerReceiver(mountInstance, mountInstance.getIntentFilter());
Everything is fine and dandy and working as expected. I can unmount and remount my SD card and my setMounted method is fired as appropriate. The problem I have is, is that my doPerformQuery() method returns 0 results after the SD card is mounted. If I change the code to:
Thread.sleep(5000);
doPerformQuery();
Then it will work, occasionally. This gives the SD card 5 seconds to finish "preparing". I want to know when the SD card has finished preparing and can be read. Currently, I'm getting the intent when the SD card is mounted, but it hasn't "prepared" itself yet, so it's not readable. Is there such an intent to register to when the SD card has finished "preparing". On a side note, I say "preparing" because that's what my phone says in the notification bar. I'm not sure if this is standard across all phones as I can't find a single thing about the SD card preparing online.
In response to our comments to your original question...
I think the logic is that when the SD card is dismounted, the content provider for various AV media (videos, music, photos etc) is cleared of anything on the SD card because the system won't know when (if ever) the same SD card will return and if it does whether it will have the same files on it. As a result, a full scan is carried out each time an SD card is installed (resulting in the 'preparing' notification).
So in your case, checking for ACTION_MEDIA_SCANNER_STARTED and most importantly the associated ACTION_MEDIA_SCANNER_FINISHED means the AV media content provider will have a current list of everything on the card.
Check the Environment.getExternalStorageState()
result (link to API).
I'm pretty sure you will get MEDIA_CHECKING
until a few seconds later. If that's correct, you can use a simple while
loop to check it and proceed when the state changes to MEDIA_MOUNTED
精彩评论