我有2个广播接收器,一个接收器用于连接/断开连接,一个接收器需要用户许可。代码如下:
public class DeviceAttachReceiver extends BroadcastReceiver {
public static final String ACTION_USB_PERMISSION = "redacted.permission";
@Override
public void onReceive(Context context, Intent intent) {
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(intent.getAction())) {
//Device was attached, ask for permission
UsbManager usbManager = (UsbManager)context.getSystemService(Context.USB_SERVICE);
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
usbManager.requestPermission(device, PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0));
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(intent.getAction())) {
//Disconnected
UsbMonitorConnection.disconnect();
}
}
}
public class UsbPermissionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (MonitorAttachReceiver.ACTION_USB_PERMISSION.equals(intent.getAction())) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false);
if (granted) {
//Permission granted, connect the device
UsbMonitorConnection.connect(context, device);
}
}
}
}
问题是,第一个接收器(连接一个)工作正常,弹出一个对话框供用户访问该设备,但第二个则不然。在Android 8之前,此方法有效。我在做什么错了?