我正在编写一个应用程序,需要检测SD卡何时通过USB挂载为磁盘驱动器或何时已被手动移除。我尝试使用广播接收器来实现此目的,但onReceive没有被调用。我的代码如下。
IntentFilter filter2 = new IntentFilter();
//filter2.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
filter2.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
filter2.addAction(Intent.ACTION_MEDIA_SHARED);
filter2.addAction(Intent.ACTION_MEDIA_REMOVED);
filter2.addAction(Intent.ACTION_MEDIA_MOUNTED);
registerReceiver(new CustomBroadcastReceiver(), filter2);
我的广播接收器如下所示...
public class CustomBroadcastReceiver extends BroadcastReceiver{
public CustomBroadcastReceiver(){
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(Intent.ACTION_MEDIA_UNMOUNTED) || action.equals(Intent.ACTION_MEDIA_SHARED) || action.equals(Intent.ACTION_MEDIA_REMOVED)){
HardwareManager.IS_MEDIA_MOUNTED = false;
}else if(action.equals(Intent.ACTION_MEDIA_MOUNTED)){
HardwareManager.IS_MEDIA_MOUNTED = true;
}else if(action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)){
HardwareManager.IN_AIRPLANE_MODE = intent.getBooleanExtra("state", false);
}
}
}
当我通过 USB 连接作为磁盘驱动器时,onReceive方法不会触发。
我做错了什么?
Intent.ACTION_UMS_CONNECTED
吗? - Chromium