Android out of memory應注意的地方

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();

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章