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();
}
上一篇:Android系统编程入门系列之硬件交互——通信硬件USB


下一篇:联想推出 YOGA 14c 锐龙版评测