3

我正在使用 usbmanager 类来管理我的 android 4.1.1 机器上的 USB 主机。对于数百个事务,一切似乎都运行良好,直到(大约 900 个事务之后)打开设备失败,无一例外地返回 null。使用分析器似乎不是内存泄漏的问题。

这就是我从我的主要活动初始化通信的方式(这样做一次):

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;
    } 

对于 900 到 1000 次调用,该测试将正常工作,之后以下调用将返回 null(无异常):

UsbDeviceConnection connection; 
try 
{
  connection = m_manager.openDevice(m_device);
}
4

2 回答 2

8

您可能只是用完了文件句柄,典型的限制是每个进程打开 1024 个文件。尝试调用close()UsbDeviceConnection参阅 doc

UsbDeviceConnection对象已分配系统资源 - 例如文件描述符 - 将仅在代码中的垃圾收集时释放。但是在这种情况下,您会在内存不足之前耗尽资源 - 这意味着尚未调用垃圾收集器。

于 2013-04-17T17:45:46.920 回答
0

尽管我在代码中只打开一次,但我在 android 4.0 上重复运行时 opendevice 失败。我有一些退出路径没有关闭资源,我假设操作系统会在进程终止时释放它。

但是,在进程终止时释放资源似乎存在一些问题-即使我终止并启动了新进程,我也曾经遇到过问题。
我终于确保在退出时释放资源并使问题消失。

于 2013-07-01T07:37:32.483 回答