即時嘗試做類似這樣的: android: how to listen to "sd card removed unexpectedly" 但onReceive的聽衆永遠不會被調用,當我沒有安裝SD卡或我刪除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);
}
我不想檢查,如果SD卡存在或不 如果(android.os.Environment.getExternalStorageState()。等於(android.os.Environment.MEDIA_MOUNTED)) 但使用接收器來代替。任何幫助,歡迎。謝謝!
您是否在清單文件中設置了您的權限? – Lukap
@Lukap我在我的清單中有android.permission.READ_PHONE_STATE –
@ con_9你是對的,對不起。 – Caner