2013-04-17 72 views
3

我使用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); 
} 

回答

7

您可能會耗盡文件句柄,每個進程的典型限制爲1024個打開的文件。 請致電close()聯繫UsbDeviceConnection,see doc

UsbDeviceConnection對象已分配系統資源 - 例如,一個文件描述符 - 僅在代碼中的垃圾回收時纔會被釋放。但在這種情況下,在耗盡內存之前,用完了ressources - 這意味着垃圾收集器尚未調用。

+0

感謝Turbo J,你的回答是正確的。我關閉並確保釋放usb端點。問題解決了。 – Gplatfrom

+0

那麼你可以接受並提出答案嗎? –

0

我曾在android 4.0上重複運行opendevice失敗,即使我只在代碼中打開一次。我有一些退出路徑沒有關閉資源,我假定操作系統會在進程終止時釋放它。

但是,似乎在進程終止時釋放資源似乎存在一些問題 - 即使在終止並啓動新進程時,我仍然遇到問題。
我終於確保在退出時釋放資源並使問題消失。