1. 程式人生 > >android 監聽USB連線狀態

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的狀態