我使用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);
}发布于 2013-04-18 01:45:47
您可能会用完文件句柄,典型的限制是每个进程有1024个打开的文件。尝试在UsbDeviceConnection上调用close(),see doc。
UsbDeviceConnection对象已经分配了系统资源-例如文件描述符-只有在代码中进行垃圾回收时才会释放这些资源。但在这种情况下,您在内存用完之前就用完了资源-这意味着垃圾收集器还没有被调用。
发布于 2013-07-01 15:37:32
我让opendevice在android4.0上反复运行失败,尽管我在代码中只打开了一次。我有一些没有关闭资源的退出路径,并且我假设操作系统会在进程终止时释放它。
然而,关于进程终止的资源释放似乎有一些问题,即使我终止并启动了一个新的进程,-I过去也会有问题。
我最终确保在退出时释放资源,并使问题消失。
https://stackoverflow.com/questions/16064798
复制相似问题