私は Eclipse を使用しており、Android フォンにアプリをインストールしました。
主な活動コード:
パッケージcom.example.usbdetection;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
UsbManager usbManager;
PendingIntent mPermissionIntent;
UsbDevice usbDevice;
Intent intent;
final String ACTION_USB_PERMISSION = "com.example.usbdetection.USB_PERMISSION";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
usbDevice = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
usbManager.requestPermission(usbDevice, mPermissionIntent);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (usbDevice != null) {
// call method to set up device communication
int deviceId = usbDevice.getDeviceId();
int productId = usbDevice.getProductId();
Log.i("device id", "****" + deviceId);
Log.i("product id", "****" + productId);
} else {
Log.i("device id", "No USB device");
}
} else {
Log.d("shiv", "permission denied for device ");
}
}
}
}
};
}
マニフェスト ファイル:
<uses-feature android:name="android.hardware.usb.host" />
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.usbdetection.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="@xml/device_filter" />
</activity>
</application>
アプリを実行して USB を接続すると、何も表示されません。どうしたの?。
どんな助けでも大歓迎です:)