我正在为UsbInterfacing构建一个应用程序,我需要在我的应用程序运行时连续枚举USB设备..我需要在连接和断开连接时得到通知..我的usb设备的供应商ID是1204,product-id是64905 ..枚举有效一次。拔下设备并将其重新插入后,将无法工作.Below是我的代码:
package com.example.enumerate;
import java.util.HashMap;
import java.util.Iterator;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
public class Enumerate extends Activity {
UsbDevice device;
Iterator<UsbDevice> deviceIterator;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
//My onResume method
@Override
protected void onResume()
{
super.onResume();
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
deviceIterator = deviceList.values().iterator();
//my UsbIterator
while(deviceIterator.hasNext())
{
device = deviceIterator.next();
}
if(device.getProductId()==64905) //my device ProductId
{
Toast t=Toast.makeText(this,"Connected",2000);
t.show();
}
else
{
Toast t=Toast.makeText(this,"Not Connected",2000);
}
}
}
答案 0 :(得分:0)
您需要创建一个BroadcastReceiver来侦听系统在连接或分离设备时发送的各种广播操作。 UsbManager文档显示了各种动作常量。
内部Activity
类的基本模板BroadcastReceiver
可能如下所示......
public class MyActivity extends Activity {
MyReceiver myReceiver = null;
IntentFilter intentFilter = null;
boolean isReceiverRegistered = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intentFilter = new IntentFilter();
// Add any or all of the following 'actions' to the IntentFilter
// depending on what you need to track.
intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
}
@Override
protected void onResume() {
super.onResume();
if (!isReceiverRegistered) {
myReceiver = new MyReceiver();
registerReceiver(myReceiver, intentFilter);
isReceiverRegistered = true;
}
}
@Override
protected void onPause() {
super.onPause();
if (isReceiverRegistered) {
unregisterReceiver(myReceiver);
myReceiver = null;
isReceiverRegistered = false;
}
}
private class MyReceiver extends BroadcastReceiver {
@Override
protected void onReceive(Context context, Intent intent) {
String action, accessory, device, permissionGranted;
action = intent.getAction();
// Make sure you check to see if any of the strings are null
// just in case the Intent isn't carrying any of them
accessory = intent.getStringExtra(UsbManager.EXTRA_ACCESSORY);
device = intent.getStringExtra(UsbManager.EXTRA_DEVICE);
permissionGranted = intent.getStringExtra(UsbManager.EXTRA_PERMISSION_GRANTED);
// Do what you need to do based on the action and extras...
}
}
}