Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/212.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android:检测插入的USB闪存驱动器_Android_Broadcastreceiver - Fatal编程技术网

Android:检测插入的USB闪存驱动器

Android:检测插入的USB闪存驱动器,android,broadcastreceiver,Android,Broadcastreceiver,有没有办法检测USB闪存驱动器何时插入Android设备?我能够用广播接收器检测SD卡,但它不适用于USB。我想避免投票 注册接收器的代码: private void RegisterUpdateReceiver() { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("android.intent.action.MEDIA_MOUNTED"); intentFilter.add

有没有办法检测USB闪存驱动器何时插入Android设备?我能够用广播接收器检测SD卡,但它不适用于USB。我想避免投票

注册接收器的代码:

private void RegisterUpdateReceiver()
{
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("android.intent.action.MEDIA_MOUNTED");
    intentFilter.addDataScheme("file");
    myReceiver = new MyReceiver();
    this.registerReceiver(myReceiver, intentFilter);
}
接收器代码:

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

在SDK级别,Android没有USB驱动器的概念。没有关于它们应该安装在哪里、何时出现/消失的广播等规则。也许在未来的Android版本中会出现一些这方面的标准化,但今天还没有。

如果检测到连接和分离USB将起作用,则可以使用“安卓.硬件.USB.动作.USB\U设备\U连接”。
确保在清单中也添加了接收者的定义和意图过滤器。

这是AndroidManifest.xml中接收者的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>

这就是我在Android 6.0上工作的方式。 基本上,我们需要检测的是驱动器何时挂载,这可以通过“安卓.意图.动作.媒体挂载”的ACTION_MEDIA_挂载来完成

按照以下步骤操作:

  • 为“操作\u USB\u设备\u连接”注册广播接收器
  • 为“操作\媒体\安装”注册广播接收器
  • 当收到“操作\u USB\u设备\u已连接”操作时,寻求使用设备的权限。 然后,您将收到“ACTION\u MEDIA\u MOUNTED”的广播
  • 你可以参考:


    注意:为单独安装的操作\媒体\注册广播接收器不起作用。因此使用广播“ACTION\u USB\u DEVICE\u ATTACHED”以获得许可。

    Logcat显示了一些与USB装载相关的事件,但我无法在SDK级别检测到这一点。听起来你说的是对的。W/MountService(931):getVolumeState(/mnt/usbdisk):未知的卷E/VoldConnector(931):错误处理“605卷usbdisk/mnt/usbdisk状态从3(检查)更改为4(已装入)”,这里有什么好运气吗,我还使用了ACTION\u MEDIA\u REMOVED和其他与接收器相关的USB装载和卸载…但没有任何功能…但在命令提示符中显示USB日志?@Shubh:从Android 4.2开始,所写的答案仍然是准确的。我得到了答案。我在接收器类中添加了标记。它对我有效。@androiddeveloper:抱歉,但我不知道。在我的智能手机上,那个事件发生在硬盘安装之前。我已经等了一秒钟,然后才可以使用这个驱动器。你在问题中发布的代码非常适合我在装有Android 6的Allwinner开发板上检测usb驱动器(通过usb OTG)