First, the demand
In the Android should develop the process, the use of USB communication, need to apply monitoring USB device Plug and unplug, so as to refresh the USB device list.
Second, the realization
In use, register and unregister are required.
public class Usbbroadcastreceiver extends Broadcastreceiver {
Private Onusblistener Usblistener;
@Override
public void OnReceive (context context, Intent Intent) {
String action = Intent.getaction ();
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals (ACTION) | |
UsbManager.ACTION_USB_DEVICE_ATTACHED.equals (ACTION)) {
Usblistener.onstatechanged ();
}
}
public void Registerusbreceiver (context context) {
Intentfilter filter = new Intentfilter ();
Filter.addaction (usbmanager.action_usb_device_attached);
Filter.addaction (usbmanager.action_usb_device_detached);
Context.registerreceiver (this, filter);
}
public void Unregisterusbreceiver (context context) {
Context.unregisterreceiver (this);
}
public void Setusblistener (Onusblistener usblistener) {
This.usblistener = Usblistener;
}
@FunctionalInterface
Public interface Onusblistener {
void Onstatechanged ();
}
}
Monitor USB plug-and-Unplug in Android