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 http://developer.android.com/guide/topics/usb/host.html 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:
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
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 ";
}
}
}
}
};
我登记的法典部分:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
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<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while(deviceIterator.hasNext())
{
device = deviceIterator.next();
mUsbManager.requestPermission(device, mPermissionIntent);
}
// ...
if(device!=null)
{
// ...
}
else
{
// ...
}
tv.setText(devMessage);
}
没有人知道为什么发生这种情况,我会做什么错?