[英]listener for sd-card removal
我想尝试做类似的事情: 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);
}
我不想通过if(android.os.Environment.getExternalStorageState()。equals(android.os.Environment.MEDIA_MOUNTED))检查sdcard是否存在,而是使用接收器。 欢迎任何帮助。谢谢!
好吧我认为我发布的代码是针对行动而不是状态和工作正常。
来自文件:
android.content.Intent.ACTION_MEDIA_REMOVED广播操作:已删除外部媒体。 已删除介质的装入点的路径包含在Intent.mData字段中。
所以我期待的(我错了,看到问题的前两行),如果我没有SDCard(即它已被删除)然后我启动应用程序我会接到电话暗示我没有SD卡(我知道听起来很闷;))。 意图是动作(而不是状态)。因此,如果我在应用程序处于活动状态时删除了SD卡,我会收到回调。 谢谢你的时间拉斯维加斯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.