我使用usbmanager類來管理我的android 4.1.1機器上的USB主機。對於幾百個事務,所有似乎都能很好地工作,直到(約900個事務之後)打開設備失敗,無一例外地返回null。 使用探查器它似乎不是內存泄漏的問題。經過幾百次成功嘗試,usbManager openDevice調用失敗
這是我從我的主要活動初始化通信(這樣做一次):
public class MainTestActivity extends Activity {
private BroadcastReceiver m_UsbReceiver = null;
private PendingIntent mPermissionIntent = null;
UsbManager m_manager=null;
DeviceFactory m_factory = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
m_UsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
// call your method that cleans up and closes communication with the device
Log.v("BroadcastReceiver", "Device Detached");
}
}
}
};
registerReceiver(m_UsbReceiver, filter);
m_manager = (UsbManager) getSystemService(Context.USB_SERVICE);
m_factory = new DeviceFactory(this,mPermissionIntent);
}
,這是我的測試代碼:
ArrayList<DeviceInterface> devList = m_factory.getDevicesList();
if (devList.size() > 0){
DeviceInterface devIf = devList.get(0);
UsbDeviceConnection connection;
try
{
connection = m_manager.openDevice(m_device);
}
catch (Exception e)
{
return null;
}
測試將工作就OK了900到1000次呼叫,在此之後,以下呼叫將返回空(無一例外):
UsbDeviceConnection connection;
try
{
connection = m_manager.openDevice(m_device);
}
感謝Turbo J,你的回答是正確的。我關閉並確保釋放usb端點。問題解決了。 – Gplatfrom
那麼你可以接受並提出答案嗎? –