Android的OutOfMemory解決

來源:互聯網
上載者:User

標籤:android   開發   背景圖片   資源   

安卓開發中應注意記憶體的釋放,一旦載入圖片或其他佔用太多記憶體,此時就會發生OOM錯誤,即記憶體泄露。


在開發中,尤其應注意圖片資源的釋放。

1。背景圖片和ImageView釋放------尤其注意圖片資源

如:

  1. <?xml version="1.0" encoding="utf-8"?>

  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  3.               android:orientation="vertical"

  4.               android:background="@drawable/main_background"

  5.               android:id="@+id/mian_bg"

  6.               android:scaleType="fitXY"

  7.               android:gravity="center"

  8.               android:layout_width="fill_parent"

  9.               android:layout_height="fill_parent"

  10.         >

  11.    <ImageView

  12.             android:layout_gravity="center"

  13.             android:src="@drawable/img_main_roll0"

  14.             android:id="@+id/main_cion"

  15.             android:layout_width="180dp"

  16.             android:layout_height="180dp"/>

  17.       

  18. </<LinearLayout>


  19. 先擷取圖片控制項:

  20. public ImageView imageView;

  21. public LinearLayout linearLayout;


  22. imageView=(ImageView)findViewById(R.id.main_cion);

  23. linearLayout=(LinearLayout)findViewById(R.id.mian_bg);

  24. 應在次Activity銷毀時釋放

  25. protected void onDestroy() {

  26.         super.onDestroy();

  27.         imageView.setImageBitmap(null);//釋放

  28.         linearLayout.setBackground(null);

  29.         System.gc();//通知進行回收

  30.     }


  31. 使用Bitmap記得不用時調用回收

  32. bitmap.recycle();



  33. 總結:

  34. 無論你是在xml中布局使用了:


  35. android:background   ,


  36. 還是在java代碼中調用了:


  37. setBackground( background );-------API16+


  38. setBackgroundDrawable( background)--------API16-


  39. setBackgroundResource( resid)


  40. 的方式去設定了背景圖片.


  41. 使用的時候,請調用一下對應的方法: 

  42. setBackgroundResource和 android:background → setBackgroundResource(0);


  43. setBackgroundDrawable( background) → setBackgroundDrawable (null)


  44. setBackground ( background ) → setBackground ( null )  

  45. 然後再onDestory中調用System.gc();


複製代碼

2.確定不用的List,數組等參數

釋放:Obj=null即可,list先clear(),在令其等於null;如記憶體緊張,可及時調用Syetem.gc()通知進行回收


Android的OutOfMemory解決

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.