成长来源于坚持不懈的努力。每天都在进步,不在乎进步的多少,量变最终形成质变!
usb host模式的书面叙述我就不多说了,我就谈谈我的理解,其实usb host模式其实就是电脑的usb口模式,这情况你可以改变硬件外接电脑的usb口,也可以是原来的usb口外接转换口,如OTG。这时候用SD的拔插广播
Intent.ACTION_MEDIA_MOUNTED //sd卡挂载
Intent.ACTION_MEDIA_EJECT //sd 卡移除
这时候就要用到
android.hardware.usb.action.USB_DEVICE_ATTACHED android.hardware.usb.action.USB_DEVICE_DETACHED
网上对于这两个广播的描述都是千篇一律,其实也两个广播可以静态监听,也可以动态监听,还可以实行设备过滤。
和其他广播一样,只需要在AndroidManifest.xml里面注册这两个广播就可以了
public class braost extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
Log.e("pangsheng", "静态广播接收器设备插入");
} else if (action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
Log.e("pangsheng", "静态广播接收器设备拔出");
}
}
}
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
intentFilter.addDataScheme("file");
registerReceiver(broadcastRec, intentFilter);
private final BroadcastReceiver broadcastRec = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
Log.e("pangsheng", "usb attached");
}
if (action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
Log.e("pangsheng", "usb unattached ");
}
}
};
这个其实就是静态注册,只不过是可以自定义打开自己的activity,多用于游戏设备,还可以实现弹窗让用户选择
在AndroidManifest.xml对应的activity加上
然后在xml文件夹建立
device_filter.xml
activity
private static final String ACTION_USB_DEVICE_PERMISSION =
"com.android.accessorydisplay.sink.ACTION_USB_DEVICE_PERMISSION";//用户确认时候打开
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
filter.addAction(ACTION_USB_DEVICE_PERMISSION);
mReceiver = new DeviceReceiver();
registerReceiver(mReceiver, filter);
class DeviceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
String action = intent.getAction();
if (action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
Log.e("pangsheng", "");
} else if (action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
Log.e("pangsheng", "");
} else if (action.equals(UsbManager.ACTION_USB_DEVICE_PERMISSION)) { Log.e("pangsheng", "权限,用户确认");
}
} } }