为ACTION_USB_DEVICE_DETACHED注册的广播接收器工作正常,但同样不适用于ACTION_USB_DEVICE_ATTACHED。问题是当触发ACTION_USB_DEVICE_ATTACHED的意图时,不会调用onReceive()。
这是我的代码,我在onCreate()
中注册了接收者registerReceiver(mUsbDeviceReceiver, new IntentFilter(
UsbManager.ACTION_USB_DEVICE_DETACHED));
registerReceiver(mUsbDeviceReceiver, new IntentFilter(
UsbManager.ACTION_USB_DEVICE_ATTACHED));
以下是BroadcastReceiver类的代码:
private final BroadcastReceiver mUsbDeviceReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getBaseContext(), "onRecieve", Toast.LENGTH_SHORT).show();
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
Toast.makeText(
SUSB_Serial.this,
"ACTION_USB_DEVICE_ATTACHED:", Toast.LENGTH_LONG)
.show();
Log.d("dj", "USB attached");
connectUsb();
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
try{
UsbDevice tempDevice = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if(tempDevice != null){
if(tempDevice.getProductId() == device.getProductId()
&& tempDevice.getVendorId() == device.getVendorId()){
Toast.makeText(SUSB_Serial.this,
"ACTION_USB_DEVICE_DETACHED:",
Toast.LENGTH_LONG).show();
Log.d("dj", "USB detached");
AlertDialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(SUSB_Serial.this);
builder.setMessage("Data reading failed, connect back the devices to continue").setTitle("Device Detached!!").
setPositiveButton("Okay", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog = builder.create();
dialog.show();
Log.d("dj", "Releasing resources of USB");
releaseUsb();
}
}
}catch(Exception ex){
Log.d("dj", "Missing device reference");
ex.printStackTrace();
}
}
}
};
答案 0 :(得分:0)