我正在编写一个应用程序,它需要检测 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 方法不会触发。
我究竟做错了什么 ?