sd-card删除的监听者

时间:2011-09-26 08:22:08

标签: android

我试图做类似的事情: android: how to listen to "sd card removed unexpectedly" 但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);
     }

我不想检查sdcard是否存在 如果(android.os.Environment.getExternalStorageState()。等于(android.os.Environment.MEDIA_MOUNTED)) 但请改用接收器。欢迎任何帮助。谢谢!。

1 个答案:

答案 0 :(得分:3)

好的,我认为我发布的代码是针对动作&不是国家和工作正常。

来自文档:

  

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

所以我期待的(我错了,看到问题的前两行),如果我没有SDCard(即它已被删除)然后我启动应用程序我会接到电话暗示我没有SD卡(我知道听起来很闷;))。意图是动作(而不是状态)。因此,如果我在应用程序处于活动状态时删除了SD卡,我会收到回调。 谢谢你的时间拉斯维加斯。

相关问题