SD卡删除意图不起作用

时间:2016-12-01 13:52:11

标签: android android-sdcard intentfilter android-broadcastreceiver

第一次在这里发帖我希望我做得对。我试图检测SD卡何时从设备中移除,我的广播接收器在旧的ICS平板电脑上工作正常(我能够获得MEDIA_UNMOUNTED,BAD_REMOVAL等,意图动作)但在另一个平板电脑 android 4.2 当我移除SD卡时没有任何反应,没有播放以下任何意图行为:

  • MEDIA_BAD_REMOVAL

  • MEDIA_EJECT

  • MEDIA_REMOVED

  • MEDIA_UNMOUNTED

我这里只找到了1个相关问题,但解决方法是添加dataScheme" file"我已经尝试过了。这是我的代码:

    private BroadcastReceiver deviceCardsBroadcastReceiver;
    private IntentFilter sdCardIntentFilter;

    sdCardIntentFilter = new IntentFilter();
    sdCardIntentFilter.addAction(MEDIA_REMOVED);
    sdCardIntentFilter.addAction(MEDIA_UNMOUNTED);
    sdCardIntentFilter.addAction(MEDIA_BAD_REMOVAL);
    sdCardIntentFilter.addAction(MEDIA_EJECT);
    sdCardIntentFilter.addDataScheme("file");

    registerReceiver(deviceCardsBroadcastReceiver, sdCardIntentFilter);

    deviceCardsBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

                switch (intent.getAction()) {

                    case MEDIA_BAD_REMOVAL:
                    case MEDIA_EJECT:
                    case MEDIA_REMOVED:
                    case MEDIA_UNMOUNTED:
                        Log.i("SD CARD REMOVED");
                        break;
                    default:
                        break;
                }
            }
    };

1 个答案:

答案 0 :(得分:0)

您必须在清单中注册BroadcastReceiver,如下所示

<application>
<receiver android:name=".BroadcastSDCard">
  <intent-filter>
    <action android:name="android.intent.action.MEDIA_UNMOUNTED" />
    <action android:name="android.intent.action.MEDIA_REMOVED" />
    <action android:name="android.intent.action.MEDIA_EJECT" />
    <action android:name="android.intent.action.MEDIA_BAD_REMOVAL" />
    <data android:scheme="file" />
  </intent-filter>
</receiver>
</application>

然后创建一个名为BroadcastSDCard。class的新类,并使用该类。

public class BroadcastSDCard extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
       // do your stuff
    }
}

您仍然可以使用现有代码

private BroadcastSDCard deviceCardsBroadcastReceiver;
private IntentFilter sdCardIntentFilter;

deviceCardsBroadcastReceiver = new BroadcastSDCard();
sdCardIntentFilter = new IntentFilter();
sdCardIntentFilter.addAction(MEDIA_REMOVED);
sdCardIntentFilter.addAction(MEDIA_UNMOUNTED);
sdCardIntentFilter.addAction(MEDIA_BAD_REMOVAL);
sdCardIntentFilter.addAction(MEDIA_EJECT);
sdCardIntentFilter.addDataScheme("file");

registerReceiver(deviceCardsBroadcastReceiver, sdCardIntentFilter);

另外,请勿忘记在onDestroy()方法中取消注册,否则会泄漏。

@Override
    public void onDestroy() {
        super.onDestroy();
        if (deviceCardsBroadcastReceiver!= null)
            unregisterReceiver(updateBroadcast);
    }