AndroidのUSBホスト機能を試す
今や死語になりつつ有るAndroid 3.1 Honeycombから対応している機能。ちょっと気になったので使ってみます。
When your Android-powered device is in USB host mode, it acts as the USB host, powers the bus, and enumerates connected USB devices. USB host mode is supported in Android 3.1 and higher.
まずはAndroidManifestから実装
USBホスト機能を使うには、何はともあれuses-feature
でUSBホストを使うことを宣言しておきます。
<uses-feature android:name="android.hardware.usb.host" />
USBホストでデバイスが接続されたことを検知してActivityを起動できるIntentFilterもありますが、今回は使わないので何もしません。
If you want your application to be notified of an attached USB device, specify an <intent-filter> and <meta-data> element pair for the android.hardware.usb.action.USB_DEVICE_ATTACHED intent in your main activity. The <meta-data> element points to an external XML resource file that declares identifying information about the device that you want to detect.
次にJavaの実装
UsbManager
インスタンスを生成して、そこからUsbDevice
クラスで表現される接続されているUSBデバイス情報を取得します。
適当に結果表示用のTextView
とUsbManager
を宣言しておいて、
private TextView mTextView; private UsbManager mUsbManager;
Context#getSystemService()
でUsbManager
インスタンスを持ってきます。
mUsbManager = (UsbManager) getSystemService(USB_SERVICE);
UsbManager#getDeviceList()
で接続されているデバイスのリストを取得して、その結果をそのままTextView
に出力してみます。
mTextView = (TextView) findViewById(R.id.textview); HashMap<String, UsbDevice> deviceList= mUsbManager.getDeviceList(); if(deviceList == null || deviceList.isEmpty()){ mTextView.setText("no device found"); }else{ String string = ""; for(String name : deviceList.keySet()){ string += name + "\n"; } mTextView.setText(string); }
いざ起動
普通に何もアプリを起動すると・・・
まぁ、想定通りです。 スマホにUSBリーダライタを繋いでみます。
ELECOM メモリカードリーダー/ライター スマホ・タブレット用 microBケーブル SD+microSD ブラック MRS-MB06BK
すると、こんな感じに表示されます。
通信はできていないもの、アプリ上で接続されたデバイスを認識することはできました。まずはここまで。