android 监听USB连接状态

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() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String 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的状态

猜你喜欢

转载自bgj.iteye.com/blog/2167280