Note that there are some explanatory texts on larger screens.

plurals
  1. POBroadcastReceiver fires after the activity is already created
    primarykey
    data
    text
    <p>I want to use a BroadcastReceiver to get permission to communicate with a USB device. I am trying to implement it the same way it is done on android website <a href="http://developer.android.com/guide/topics/usb/host.html" rel="nofollow">http://developer.android.com/guide/topics/usb/host.html</a> It all works, kind of. But the broadcastReceiver is fireing only after the main activity is created. Which means I am able to communicate with the device only after close the app and open it again (when I don't unregister the broadcastReceiver, when I do I can't communicate at all). What can be the reason? My code is like this:</p> <p>private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {</p> <pre><code> public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_USB_PERMISSION.equals(action)) { synchronized (this) { device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { if(device != null) { //things I do when the permission is granted } } else { devMessage = "permission denied for device "; } } } } }; </code></pre> <p>The part of the code where I register it:</p> <p>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); </p> <pre><code> mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE); mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); filter = new IntentFilter(ACTION_USB_PERMISSION); registerReceiver(mUsbReceiver, filter); HashMap&lt;String, UsbDevice&gt; deviceList = mUsbManager.getDeviceList(); Iterator&lt;UsbDevice&gt; deviceIterator = deviceList.values().iterator(); while(deviceIterator.hasNext()) { device = deviceIterator.next(); mUsbManager.requestPermission(device, mPermissionIntent); } // ... if(device!=null) { // ... } else { // ... } tv.setText(devMessage); } </code></pre> <p>Does anyone know why is this happening, what I might be doing wrong?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload