Android USB设备插拔监听

USB设备插拔监听

普通USB设备

此类USB设备插拔监听,网络上很容易搜到。注册广播,此处只给出静态注册:

<receiver
  android:name=".USBReceiver" >
  <intent-filter>
    <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/>
    <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED"/>
  </intent-filter>
</receiver>
public class USBReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
    switch (action) {
      // 插入USB设备
      case UsbManager.ACTION_USB_DEVICE_ATTACHED:
        Log.i(TAG, "USB设备连接");
        break;
      // 拔出USB设备
      case UsbManager.ACTION_USB_DEVICE_DETACHED:
        Log.i(TAG, "USB设备断开");
        break;
      default:
        break;
    }
  }
}

输入型USB设备

输入型设备,包括扫码枪、键盘、鼠标等。使用普通的USB插拔广播,无法监听到此类设备的插拔。
需使用InputManager.InputDeviceListener进行监听。

public class InputListener implements InputManager.InputDeviceListener {
  @Override public void onInputDeviceAdded(int id) {
  	// Called whenever an input device has been added to the system.
     Log.d(TAG, "onInputDeviceAdded");
  }

  @Override public void onInputDeviceRemoved(int id) {
  	// Called whenever an input device has been removed from the system.
    Log.d(TAG, "onInputDeviceRemoved");
  }

  @Override public void onInputDeviceChanged(int id) {
  	// Called whenever the properties of an input device have changed since they were last queried.
    Log.d(TAG, "onInputDeviceChanged");
  }
}

注册监听:

InputManager manager = (InputManager) getSystemService(Context.INPUT_SERVICE);
manager.registerInputDeviceListener(this, null);

解注册:

manager.unregisterInputDeviceListener(this);

基本使用,获取已插入输入型设备:

int[] ids = inputManager.getInputDeviceIds();
for (int id : ids) {
  InputDevice device = inputManager.getInputDevice(id);  
  String deviceName = device.getName();
  int pid = device.getProductId();
  int vid = device.getVendorId();
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值