我想使用 BroadcastReceiver 来获得与 USB 设备通信的权限。我正在尝试以与在 android 网站http://developer.android.com/guide/topics/usb/host.html上相同的方式实现它, 这一切都有效。但是广播接收器仅在创建主要活动后才会触发。这意味着我只能在关闭应用程序并再次打开它后才能与设备通信(当我不取消注册广播接收器时,我根本无法通信)。可能是什么原因?我的代码是这样的:
私有最终广播接收器 mUsbReceiver = 新广播接收器() {
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); 设置内容视图(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);
}
有谁知道为什么会这样,我可能做错了什么?