我编写了一个简单的应用程序来向通过 USB 连接到 Android 4.0 平板电脑的 USB 打印机发送命令。出于某种原因,我无法通过获取权限来声明接口并打开连接。这是相关代码:
public class TestPrintActivity extends Activity {
private UsbManager mUsbManager;
private UsbDevice mDevice;
private UsbDeviceConnection mConnection;
private UsbInterface mInterface;
private UsbEndpoint mBulkIn;
private UsbEndpoint mBulkOut;
private static final String ACTION_USB_PERMISSION =
"com.demo.xprinter.USB_PERMISSION";
private PendingIntent mPermissionIntent;
private BroadcastReceiver mUsbReceiver;
@Override
private static final String ACTION_USB_PERMISSION =
"com.demo.printerDemo.USB_PERMISSION";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_print);
mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
registerReceiver(mUsbReceiver, filter);
mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
//call method to set up device communication
openPort(device);
}
}
else {
Toast.makeText(getApplicationContext(), "Denied!", Toast.LENGTH_SHORT).show();
}
}
}
}
};
}
public void onResume() {
super.onResume();
HashMap<String,UsbDevice> deviceList = mUsbManager.getDeviceList();
for (HashMap.Entry<String,UsbDevice> entry : deviceList.entrySet()) {
UsbDevice aDevice = entry.getValue();
if ((aDevice.getProductId() == 8965) && (aDevice.getVendorId() == 1659) ){
if (mUsbManager.hasPermission(aDevice))
openPort(aDevice);
else
mUsbManager.requestPermission(aDevice, mPermissionIntent);
break;
}
}
}
这是清单的相关部分:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.demo.printerDemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<uses-feature android:name="android.hardware.usb.host"/>
我已经配置了设备,以便在连接打印机时启动我的应用程序,并且在枚举(onResume())期间找到设备并调用权限请求。但是,无论出于何种原因,我从来没有看到“请求权限”对话框(我在网上看到过它的屏幕截图),也没有调用 onReceive()。任何想法为什么会发生这种情况?