对于我的应用程序,我需要让 android 设备充当 USB 主机。它需要从 USB 连接的设备发送和接收数据。我在 Android Developers Site 浏览了 USB Host,并开发了示例代码如下:
主.java
public class UsbDemoProjActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "button click", 30).show();
Intent it = new Intent(UsbDemoProjActivity.this,Second.class);
startActivity(it);
}
});
}
}
二.java:
public class Second extends Activity{
UsbDevice device;
UsbManager mUsbManager;
PendingIntent mPermissionIntent;
private static String ACTION_USB_PERMISSION ="com.android.example.USB_PERMISSION";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("111111111");
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
ACTION_USB_PERMISSION ="com.android.example.USB_PERMISSION";
System.out.println("2222222222");
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
device = deviceList.get("deviceName");
System.out.println("33333333333");
mPermissionIntent = PendingIntent.getBroadcast(this, 0,
new Intent(ACTION_USB_PERMISSION), 0);
System.out.println("444444444444");
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
System.out.println("555555555555");
registerReceiver(mUsbReceiver, filter);
System.out.println("66666666666");
mUsbManager.requestPermission(device, mPermissionIntent);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
System.out.println("7777777777777");
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
System.out.println("88888888888");
UsbDevice device = (UsbDevice)intent.getParcelableExtra(
UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
System.out.println("99999999999999");
//call method to set up device communication
}
} else {
//Log.d(TAG, "permission denied for device " + device);
System.out.println("permission denied for device" + device);
}
}
}
}
};
}
但是,当我单击Main.java页面中的按钮时,它显示错误:
不幸的是,USBDemoProj 已停止
并且在 logcat 中显示错误,如下图所示,但这里显示的system.output()
行是在Second.java类中声明的。谁能帮我我的应用程序中的错误是什么?
另外,我是否在示例代码中使用了正确的方法来访问 USB 主机模式下的设备?谁能给我一个更好的方法?