Skip to content

Instantly share code, notes, and snippets.

@sreelallalu
Last active December 8, 2023 22:42
Show Gist options
  • Save sreelallalu/f1f122c602fd0bd554abd4ca3251ad97 to your computer and use it in GitHub Desktop.
Save sreelallalu/f1f122c602fd0bd554abd4ca3251ad97 to your computer and use it in GitHub Desktop.
Android USB detection
<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.permission.USB_PERMISSION" />
<activity android:name=".activities.MainActivity"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="@xml/device_filter" />
</activity>
<resources>
<!-- Accept all device VID/PID combinations -->
<usb-device />
</resources>
private void registerUSBBroadCast() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
registerReceiver(mUsbReceiver, filter);
}
BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_ATTACHED == action) {
Log.i(TAG, "BroadcastReceiver USB Connected");
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
}
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED == action) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
Log.i(TAG, "BroadcastReceiver USB Disconnected");
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment