1.AndroidMainifest.xml注册监听广播
<receiver android:name=".view.SdcardReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MEDIA_MOUNTED" />
<action android:name="android.intent.action.MEDIA_UNMOUNTED" />
<data android:scheme="file" />
</intent-filter>
</receiver>
2.代码处理广播
public class SdcardReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(action.equals(Intent.ACTION_MEDIA_MOUNTED)){
Log.e("MainActivity","插入sdcard");
}else if(action.equals(Intent.ACTION_MEDIA_UNMOUNTED)){
Log.e("MainActivity","拔出sdcard");
}else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
Log.e("MainActivity", "拔出usb了");
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
} else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
Log.e("MainActivity", "插入usb了");
}
}
}
Android 监控USB插拔事件和sdcard卡插拔事件
最新推荐文章于 2021-08-20 00:32:58 发布