I am using the following code:
private boolean statusUSB = false;
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action != null) {
switch (action) {
case UsbManager.ACTION_USB_DEVICE_DETACHED:
final UsbDevice detDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
final String detMsg="Device DEtached";
statusUSB = false;
Toast.makeText(context, "USB Disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbManager.ACTION_USB_DEVICE_ATTACHED:
case UsbManager.ACTION_USB_ACCESSORY_ATTACHED:
final UsbDevice attDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
final String attMsg="Device atached";
statusUSB = true;
Toast.makeText(context, "USB Connected", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
};
To detect when the USB port is connected or disconnected, apart from that I have also inserted a flag:
statusUSB = true/false
Then use it in my menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate( R.menu.main, menu );
if (statusUSB == true){
// Opcion1
}
if (statusUSB == false){
//Opcion2
}
return true;
}
The fact is that Android detects both conditions when the USB port is connected and disconnected, but the flag does not change or I can not read this value in my menu, I am doing well or there is another way to feed this flag