前言
此博客讲解Usb插入的设备信息获取
USB线
private fun initUsbReceiver() { val filter = IntentFilter() filter.addAction("android.hardware.usb.action.USB_STATE") mUsbBroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val action = intent.action if (action == "android.hardware.usb.action.USB_STATE") { val connected = intent.extras.getBoolean("connected") if (connected) { Toast.makeText(this@UsbActivity, "USB已连接", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this@UsbActivity, "USB已断开", Toast.LENGTH_SHORT).show() } } } } registerReceiver(mUsbBroadcastReceiver, filter) } private fun unregisterUsbReceiver() { unregisterReceiver(mUsbBroadcastReceiver) }
普通USB设备(U盘)
private fun initUsbDeviceReceiver() { val filter = IntentFilter() filter.addAction("android.hardware.usb.action.USB_DEVICE_ATTACHED") filter.addAction("android.hardware.usb.action.USB_DEVICE_DETACHED") mUsbBroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val action = intent.action if (action == "android.hardware.usb.action.USB_DEVICE_ATTACHED") { val usbManager: UsbManager = getSystemService(Context.USB_SERVICE) as UsbManager val deviceList = usbManager.deviceList Log.e("zh", "设备连接 设备数目:${deviceList.size}") deviceList.forEach { Log.e("zh", " 设备:${it}") } } if (action == "android.hardware.usb.action.USB_DEVICE_DETACHED") { val usbManager: UsbManager = getSystemService(Context.USB_SERVICE) as UsbManager val deviceList = usbManager.deviceList Log.e("zh", "设备断开 设备数目:${deviceList.size}") deviceList.forEach { Log.e("zh", " 设备:${it}") } } } } registerReceiver(mUsbBroadcastReceiver, filter) } private fun unregisterUsbDeviceReceiver() { unregisterReceiver(mUsbBroadcastReceiver) }
输入型USB设备(鼠标,键盘)
private val mInputManager by lazy { getSystemService(Context.INPUT_SERVICE) as InputManager }private fun initEnterUsbDeviceReceiver() { mInputDeviceListener = object : InputManager.InputDeviceListener { override fun onInputDeviceAdded(deviceId: Int) { val device = mInputManager.getInputDevice(deviceId) Log.e("zh", "onInputDeviceAdded: ${device.name}") } override fun onInputDeviceRemoved(deviceId: Int) { } override fun onInputDeviceChanged(deviceId: Int) { } } mInputManager.registerInputDeviceListener(mInputDeviceListener, null) } private fun unregisterEnterUsbDeviceReceiver() { mInputManager.unregisterInputDeviceListener(mInputDeviceListener) }
End