问题
Is there a way to detect when a USB flash drive is plugged into an Android device? I'm able to detect an SD card using a broadcast receiver, but it doesn't work for USB. I'd like to avoid polling.
code to register receiver:
private void RegisterUpdateReceiver()
{
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.intent.action.MEDIA_MOUNTED");
intentFilter.addDataScheme("file");
myReceiver = new MyReceiver();
this.registerReceiver(myReceiver, intentFilter);
}
receiver code:
public class MyReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (action.equals("android.intent.action.MEDIA_MOUNTED"))
{
// react to event
}
}
回答1:
Android, at the SDK level, has no concept of USB drives. There are no rules for where they should be mounted, broadcasts for when they appear/disappear, etc. Perhaps some standardization in this area will come in future Android releases, but it is not there today.
回答2:
If detecting attaching and detaching the USB will work "android.hardware.usb.action.USB_DEVICE_ATTACHED" can be used. Make sure the definition of the receiver and the intent filter is added in the manifest as well.
回答3:
This is the xml version of the receiver in the AndroidManifest.xml:
<receiver
android:name="MyMountBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MEDIA_MOUNTED"/>
<action android:name="android.intent.action.MEDIA_UNMOUNTED"/>
<data android:scheme="file" />
</intent-filter>
</receiver>
回答4:
This is how I made it work on Android 6.0. Basically, what we need to detect is when the drive is mounted which can be done by ACTION_MEDIA_MOUNTED that is "android.intent.action.MEDIA_MOUNTED".
Follow the steps below:
- Register a broadcast receiver for "ACTION_USB_DEVICE_ATTACHED"
- Register a broadcast receiver for "ACTION_MEDIA_MOUNTED"
- Seek permission for using the device when "ACTION_USB_DEVICE_ATTACHED" action is received. Then you will receive broadcast for "ACTION_MEDIA_MOUNTED"
You can refer: https://developer.android.com/reference/android/content/Intent#ACTION_MEDIA_MOUNTED
Note: Registering broadcast receiver for ACTION_MEDIA_MOUNTED alone does not work. So used broadcast "ACTION_USB_DEVICE_ATTACHED" for permission purpose.
来源:https://stackoverflow.com/questions/8088338/android-detect-usb-flash-drive-plugged-in