欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 监控USB插拔事件和sdcard卡插拔事件

程序员文章站 2022-03-08 16:11:09
1.AndroidMainifest.xml注册监听广播
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了");
          }
	}
}

本文地址:https://blog.csdn.net/baidu_41666295/article/details/114311950

相关标签: android