Android method to determine whether an SD card has been mounted
- 2020-06-23 01:58:17
- OfStack
This article illustrates how Android determines whether an SD card is mounted. Share to everybody for everybody reference. The details are as follows:
BroadcastReceiver set IntentFilter as:
Intent.ACTION_MEDIA_MOUNTED
Intent.ACTION_MEDIA_EJECT
Intent.ACTION_MEDIA_REMOVED
Then public void onReceive(Context context, Intent intent) to implement your startup logic startActivity
private final BroadcastReceiver broadcastRec = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.action.MEDIA_MOUNTED"))
//SD The card has been successfully mounted
{
imagepath =
android.os.Environment.getExternalStorageDirectory();// your SD The card path
}else
if(intent.getAction().equals("android.intent.action.MEDIA_REMOVED")
// Various unmounted states
||intent.getAction().equals("android.intent.action.ACTION_MEDIA_UNMOUNTED")
||intent.getAction().equals("android.intent.action.ACTION_MEDIA_BAD_REMOVAL"))
{
imagepath = android.os.Environment.getDataDirectory();// Your local path
}
}
};
// in IntentFilter Select the behavior you want to monitor
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
//intentFilter.addAction(Intent.ACTION_MEDIA_SHARED);
intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
//intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
//intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
intentFilter.addDataScheme("file");
registerReceiver(broadcastRec, intentFilter);// Register listening function
unregisterReceiver(broadcastRec);// Use the log off broadcast listener function
Hopefully, this article has been helpful in your Android programming.