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.
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
.