您的位置:首页 > 其它

安卓USB插入时系统识别然后直接用某个应用打开的方式

2015-12-15 20:28 387 查看
目的:USB插入的时候系统会提示是否要用某个APP来打开这个USB。

具体加入过程:

1、在manifest中加入intent-filter和meta-data

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.maowei.usb"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<uses-feature android:name="android.hardware.usb.host"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/>
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="@xml/device_filter"/>
</activity>
</application>

</manifest>


2、需要添加一个xml文件夹,然后在其中加入meta-data的resource

<?xml version="1.0" encoding="UTF-8"?>
<resources>
<usb-device/>
</resources>


这样是识别所有的USB,也可以识别你设定的USB,需要列出vendor-id和product-id

具体的看file:///D:/sdk/docs/guide/topics/connectivity/usb/host.html

就这样就可以了。

intent-filter是一个intent的过滤器,见

http://developer.android.com/intl/zh-cn/guide/topics/manifest/intent-filter-element.html

首先,一个intent-filter里面必须要有一个action(可以有多个),这样才能知道我们这个filter在接收到什么intent的时候才会响应。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: