android:如何听“sd卡意外删除”

我有一个使用SD卡内容的程序。 我想听不同的状态,如sd-card mount或sd-card意外删除。 我该怎么办 一个例子将是一个很大的帮助。

谢谢大家

您需要侦听ACTION_MEDIA_REMOVED和ACTION_MEDIA_MOUNTED 。 创建一个接收器并监听此操作。

编辑:

在您的清单文件中添加此项

      

然后创建一个MyReceiver类,它将扩展BroadcastReceiver,然后捕获这些操作并执行您想要执行的操作。

你可以使用这样的东西:

  static boolean checkSdCardStatus(final Activity activity) { String status = Environment.getExternalStorageState(); //the SD Card is mounted as read-only, but we require it to be writable. if (status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) { UIMethods.showFinalAlert(activity, R.string.sdcard_readonly); return false; } //your handset is mounted as a USB device if (status.equals(Environment.MEDIA_SHARED)) { UIMethods.showFinalAlert(activity, R.string.sdcard_shared); return false; } //no SD Card inserted if (!status.equals(Environment.MEDIA_MOUNTED)) { UIMethods.showFinalAlert(activity, R.string.no_sdcard); return false; } return true; } 

并在Activity.onStart()Activity.onResume()调用此方法。

在Manifest中创建一个接收器:

        

和相应的类文件:

 public class ExternalSDcardRemoved extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // SD card removed } } 

感谢@PravinCG

这是完整的代码。

SDCardBroadcastReceiver.java代码

 public class SDCardBroadcastReceiver extends BroadcastReceiver { private static final String ACTION_MEDIA_REMOVED = "android.intent.action.MEDIA_REMOVED"; private static final String ACTION_MEDIA_MOUNTED = "android.intent.action.MEDIA_MOUNTED"; private static final String MEDIA_BAD_REMOVAL = "android.intent.action.MEDIA_BAD_REMOVAL"; private static final String MEDIA_EJECT = "android.intent.action.MEDIA_EJECT"; private static final String TAG = "SDCardBroadcastReceiver"; @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "Intent recieved: " + intent.getAction()); if (intent.getAction() == ACTION_MEDIA_REMOVED) { Log.e(TAG, "ACTION_MEDIA_REMOVED called"); // For bundle Extras do like below // Bundle bundle = intent.getExtras(); // if (bundle != null) { // // } }else if (intent.getAction() == ACTION_MEDIA_MOUNTED){ Log.e(TAG, "ACTION_MEDIA_MOUNTED called"); }else if(intent.getAction() == MEDIA_BAD_REMOVAL){ Log.e(TAG, "MEDIA_BAD_REMOVAL called"); }else if (intent.getAction() == MEDIA_EJECT){ Log.e(TAG, "MEDIA_EJECT called"); } } } 

这是我的manifest.xml文件