android out of memory 内存泄露
推荐安卓开发神器(里面有各种UI特效和android代码库实例)
1.大量查询数据库时cursor没有关闭
错误写法:
Cursor cursor = getContentResolver().query( );
if(cursor != null)
{
cursor.moveTOFirst();
while(!cursor.isAfterLast())
{
..............
}
}
正确写法:
Cursor cursor = getContentResolver().query( );
if(cursor != null)
{
cursor.moveTOFirst();
while(!cursor.isAfterLast())
{
..............
}
cursor.close;
cursor = null;
}
2. Bitmap对象没有及时回收
因为Bitmap对象比较占内存,所以,Bitmap对象用完之后,最好使用Bitmap.recyle() 来回收Bitmap对象所占的内存。
3. 在Adapter中没有使用缓存中的convertView
错误写法:
pubic View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.listview_item_manage_bookshelves,null);
........................
}
正确写法:
pubic View getView(int position, View convertView, ViewGroup parent)
{
View view;
if(convertView == null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.listview_item_manage_bookshelves,null);
}
else
view = convertView;
........................
}
4. 根据Activity的生命周期,回收资源
在OnStop() 或者 onDestroy()方法中,对一些方法,对象回收,例如:
if(mArraryList != null)
mArrayList = null;
......................
.......................
System.gc();
System.gc();
5. 自定义的adapter等,当使用完后应该及时释放资源,将值置为null.如
adapter = null;
listview.setAdapter(null);