2017-03-21 76 views
1

我正在開發一個需要偵聽USB事件的應用程序(ACTION_USB_DEVICE_ATTACHED & ACTION_USB_DEVICE_DETACHED)。我創建了一個接收器來監聽這些操作。但是,當發生這些事件時,我的接收器不會啓動。Android USB操作(ACTION_USB_DEVICE_ATTACHED&ACTION_USB_DEVICE_DETACHED)在BroadcastReceiver中不起作用

Android清單:

<uses-feature android:name="android.hardware.usb.host" /> 

<receiver android:name=".USBEventReceiver"> 
      <intent-filter > 
       <action android:name="android.hardware.usb.action.USB_STATE"/> 
       <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/> 
       <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED"/> 
      </intent-filter> 
      <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" 
       android:resource="@xml/usb_device"/> 
      <meta-data android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" 
       android:resource="@xml/usb_device"/> 
</receiver> 

廣播接收器的onReceive方法:

public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); 
     UsbManager usbManager = (UsbManager)context.getSystemService(Context.USB_SERVICE); 

     if (intent.getExtras().getBoolean("connected")) { 
      Log.d(TAG, "onReceive: connected"); 
     } else if (!intent.getExtras().getBoolean("connected")) { 
      Log.d(TAG, "onReceive: disconnected"); 
     } 

     if (usbManager != null) Log.d(TAG, "onReceive: " + usbManager.getDeviceList().toString()); 

     if (device != null) Log.d(TAG, "USB Attached: " + device); 


     if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) { 
      Log.d(TAG, "onReceive: " + device.getManufacturerName()); 
      Log.d(TAG, "onReceive: " + device.getProductName()); 
      Log.d(TAG, "onReceive: " + device.getSerialNumber()); 
      Log.d(TAG, "onReceive: " + device.getSerialNumber()); 
     } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) { 
      Log.d(TAG, "onReceive: " + device.getManufacturerName()); 
      Log.d(TAG, "onReceive: " + device.getProductName()); 
      Log.d(TAG, "onReceive: " + device.getSerialNumber()); 
     } 

    } 
+0

難道你得到解決嗎? – RohitMat

+0

@RohitMat是的,我確實得到了一個。 –

回答

0

這個問題是老了,但我還是會採取刺傷它。爲了讓這些USB命令有一些操作,我使用了BroadCast Receiver。 ```

private final Broadcast Receiver mUsbReceiver = 
    switch(intent.getAction() { 
     case UsbService.ACTION_USB_ATTACHED: 
      //do something 
     case UsbService.ACTION_USB_DETACHED: 
      //do something 

`

在哪裏,你需要的東西,如註冊您的接收器:

private void setFilters() { 
    IntentFilter filter = new IntentFilter(); 

    //New Service Filters 
    filter.addAction(UsbService.ACTION_USB_ATTACHED); 
    filter.addAction(UsbService.ACTION_USB_DETACHED);  
    registerReceiver(mUsbReceiver, filter); 
}