android 4.4 监听USB连接状态

来源:互联网 发布:windows 大数据中心 编辑:程序博客网 时间:2024/06/11 23:44

原文链接:http://www.thinksaas.cn/group/topic/349045/

android 4.4上发现采用原来的什么Intent.ACTION_UMS_CONNECTED完全不能够检测到USB让连接状态,

翻看了一下源码,找到一个方法:

private final static String ACTION ="android.hardware.usb.action.USB_STATE";

 这个action可以在frameworks层的UsbManager.java文件中发现。

定义广播:

BroadcastReceiver usBroadcastReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubString action = intent.getAction();Toast.makeText(MainActivity.this,"aciton ="+ action, Toast.LENGTH_SHORT).show();if (action.equals(ACTION)) {boolean connected = intent.getExtras().getBoolean("connected");Toast.makeText(MainActivity.this,"aciton ="+ connected, Toast.LENGTH_SHORT).show();if (connected) {showUSBConntectStatus.setText("USB Connected!");} else {showUSBConntectStatus.setText("USB DisConnected!");}}}};

 

注册广播:

IntentFilter filter = new IntentFilter();filter.addAction(ACTION);registerReceiver(usBroadcastReceiver, filter);

 

注意的manifest中设置minSDK:

android:minSdkVersion="12"

 

在测试的过程中发现,将minSdkVersion设置为8,不能侦测到USB的状态


0 0