sd-card删除的监听者

con*_*n_9 5 android

我试图做类似的事情: android:如何听"sd卡意外删除", 但onReceive的听众永远不会被调用,当我没有安装SD卡或我删除SD卡.这是代码.

public class MyClass1  extends Activity{
    BroadcastReceiver mSDCardStateChangeListener = null;
     /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    mSDCardStateChangeListener = MyClass2.registerSDCardStateChangeListener(this);
   //some code which needs SDCard and throws unhandled exception if sdcard is not there 

}

@Override 
    protected void onDestroy () 
    {
        MyClass2.unRegisterSDCardStateChangeListener(this, mSDCardStateChangeListener);
        super.onDestroy();
    }



//in MyClass2
public static BroadcastReceiver registerSDCardStateChangeListener(Activity act) {

        BroadcastReceiver mSDCardStateChangeListener = new BroadcastReceiver() {

            @Override
            public void onReceive(Context arg0, Intent arg1) {
                 String action = arg1.getAction();
                    if(action.equalsIgnoreCase(Intent.ACTION_MEDIA_REMOVED)
                            || action.equalsIgnoreCase(Intent.ACTION_MEDIA_UNMOUNTED)
                            || action.equalsIgnoreCase(Intent.ACTION_MEDIA_BAD_REMOVAL)
                            || action.equalsIgnoreCase(Intent.ACTION_MEDIA_EJECT)) 
                    {
                        //i never come here ;(
                    //do something

                    }

            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_REMOVED);
        filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
        filter.addAction(Intent.ACTION_MEDIA_EJECT);
        filter.addDataScheme("file");
        act.registerReceiver(mSDCardStateChangeListener, filter);
        return mSDCardStateChangeListener;
 }

public static void unRegisterSDCardStateChangeListener(Activity act, BroadcastReceiver mSDCardStateChangeListener)
     {
         act.unregisterReceiver(mSDCardStateChangeListener);
     }
Run Code Online (Sandbox Code Playgroud)

我不想通过if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))检查sdcard是否存在,而是使用接收器.欢迎任何帮助.谢谢!

con*_*n_9 3

好吧,我认为我发布的代码是用于操作而不是状态并且工作正常。

来自文档:

android.content.Intent.ACTION_MEDIA_REMOVED 广播操作:外部媒体已被删除。已删除介质的安装点路径包含在 Intent.mData 字段中。

所以我所期望的是(我错了,请参阅问题的前两行),如果我没有 SDCard(即它已被早些时候删除),然后我启动应用程序,我会接到电话,暗示我没有SDCard(我知道听起来很愚蠢;))。意图是操作(而不是状态)。因此,如果我在应用程序处于活动状态时删除 SD 卡,我会收到回调。感谢您抽出时间来维加斯。