在 Android 开发中,如果你想要监听 USB 设备的连接和断开事件,通常会使用 UsbManager 类来管理和处理 USB 设备的连接。Android 提供了 BroadcastReceiver 来接收系统广播,监听 USB 设备的插拔。
-
首先,你需要在 AndroidManifest.xml 文件中声明 USB 权限和设备特性。
<uses-feature android:name="android.hardware.usb.host" />
-
通过创建一个 BroadcastReceiver 来监听系统发送的与 USB 设备连接相关的广播事件
class UsbReceiver : BroadcastReceiver() { private val TAG = "UsbReceiver" @RequiresApi(Build.VERSION_CODES.R) override fun onReceive(context: Context, intent: Intent) { // This method is called when the BroadcastReceiver is receiving an Intent broadcast. Log.i(TAG,"onReceive ${intent.action}") when(intent.action){ UsbManager.ACTION_USB_DEVICE_ATTACHED->{ Toast.makeText(context,"U盘已连接",Toast.LENGTH_SHORT).show() val path = UsbUtil.getUDiskPath(context) } UsbManager.ACTION_USB_DEVICE_DETACHED->{ Toast.makeText(context,"U盘已断开连接",Toast.LENGTH_SHORT).show() } Intent.ACTION_MEDIA_MOUNTED->{ Toast.makeText(context,"U盘已挂载",Toast.LENGTH_SHORT).show() val uri: Uri? = intent.data if (uri != null) { val mountPath: String? = uri.path Log.d(TAG, "USB device mounted at: $mountPath") } } Intent.ACTION_MEDIA_EJECT->{ Toast.makeText(context,"U盘已卸载",Toast.LENGTH_SHORT).show() } } }
-
动态注册 BroadcastReceiver
usbReceiver = UsbReceiver() var filter = IntentFilter().apply { addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED); addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); addAction(Intent.ACTION_MEDIA_MOUNTED); addAction(Intent.ACTION_MEDIA_EJECT); addDataScheme("file"); } registerReceiver(usbReceiver, filter); override fun onDestroy() { super.onDestroy() unregisterReceiver(usbReceiver) }
-
获取U盘挂载路径
@RequiresApi(Build.VERSION_CODES.R) fun getUDiskPath(mContext:Context):String{ val srgMgr = mContext.getSystemService(Context.STORAGE_SERVICE) as StorageManager val storagePaths = srgMgr.storageVolumes storagePaths.forEach { val usbPath = it.directory usbPath?.let {it1-> Log.i(TAG,"usb path ${it1.path} ${it.isRemovable}") if (it.isRemovable){ return it1.path } } } return "" }