Android detect usb storage for kitkat (4.4)

a 夏天 提交于 2019-12-17 06:18:42

问题


I've created a webview app which hosts a website within the app in the assets-directory. I want to update the website via an USBstick inserted in my tablets usbslot. I tried it first with the .MEDIA_MOUNTED broadcast which doesn't work for my android 4.4. Tablet. I've searched for an alternative and found the "MediaScannerConnection". There are several examples here, which didn't help me much, to solve my issue.

I'm looking for an easy and clean solution and a little explanation would be nice too, to detect if an USB-Storage is connected and the chance to execute some code afterwards. And how make this USB-check run all the time is a question in addition. I assume i have to put it in the OnResume method, but i'm not quite shure.


回答1:


Please post code for your BroadcastReceiver and AndroidManifest.xml.

Manifest should look something like

<application>
    <!--- ... --->
    <receiver android:name=".UsbBroadcastReceiver"
            android:exported="true"
            android:enabled="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>
</application>

Note the data tag, it's often overlooked.

In your onReceive implementation the URI to root of mount can be obtained from Intent#getData().

Also note that this will not work on Android 6.0 (M) and above. For 6.0 and above your code must request access to USB via one of two ways:

1) UsbManager#requestPermission

2) Intent#ACTION_OPEN_DOCUMENT_TREE as part of Storage Access Framework



来源:https://stackoverflow.com/questions/36208297/android-detect-usb-storage-for-kitkat-4-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!