我正在使用 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 时,它什么也没有显示。怎么了?。
任何帮助,将不胜感激 :)