• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Doubts about BroadcastReceiver

pilar

Lurker
Hi I am using the following code
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:
Code:
statusUSB

Code:
@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 the 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?
 
Here's a question for you - out of the following methods, which would you say gets executed first?

onReceive()
onCreateOptionsMenu()
 
Probably a better question to ask is, how many times is onCreateOptionsMenu() called?
Hint: If it's only called once, how would it ever know about changes in the statusUSB variable?
 
Back
Top Bottom