3

I used ACTION_MEDIA_MOUNTED and ACTION_MEDIA_UNMOUNTED to detect USB connection on Nexus 4, but I cannot receive any broadcast signal.

Here is my broadcast receiver code:

IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
filter.addDataScheme("file");

debugReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) {
            debugOn = true;
        } else if (Intent.ACTION_MEDIA_UNMOUNTED.equals(action)) {
            debugOn = false;
        }
    }
};
registerReceiver(debugReceiver, filter);

Any ideas? I also searched others questions; they said if I add

"filter.addDataScheme("file");"

I will get the signal, but I have tried and nothing was received.

Renaissance
  • 798
  • 5
  • 15
Ricky Li
  • 33
  • 1
  • 3

1 Answers1

4

Use UsbManager.ACTION_USB_DEVICE_ATTACHED and UsbManager.ACTION_USB_DEVICE_DETACHED for your intent filter.

To check for connection to PC use Intent.ACTION_BATTERY_CHANGED and onReceive intent.getInt(BatteryManager.EXTRA_PLUGGED) and see if the value is BatteryManager.BATTERY_PLUGGED_USB.

midhunhk
  • 5,560
  • 7
  • 52
  • 83
Hoan Nguyen
  • 18,033
  • 3
  • 50
  • 54
  • I tried your method, but it still cannot get anything. Do I need to remove `filter.addDataScheme("file")`? I also try `Intent.ACTION_POWER_CONNECTED` and `Intent.ACTION_POWER_DISCONNECTED`, and they can be received. But I want to detect the action that phone connecting to a PC. – Ricky Li Apr 26 '13 at 03:52
  • Hi, Hoan. This method may not tell difference between PC connection and normal charging connection because if I connect my phone with a wall charger, the value of `intent.getInt(BatteryManager.EXTRA_PLUGGED)` is still equal to `BatteryManager.BATTERY_PLUGGED_USB`. – Ricky Li Apr 26 '13 at 05:28
  • Well, In that case register for Intent.ACTION_POWER_CONNECTED which should show up when normal charging. – Hoan Nguyen Apr 26 '13 at 05:38
  • How would you check if the device is currently connected, via a single function that returns true/false? EDIT: never mind, here: http://stackoverflow.com/a/19229024/878126 – android developer Mar 14 '14 at 15:34