Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 效能優化實戰:告別記憶體溢出與耗電的六大關鍵

編輯:Android 開發實例

行動裝置的運算資源與電力始終有限,一段看似不起眼的小疏忽,往往會在實際環境中放大成災難。以下整理了六個在 Android 開發中極具代表性、卻又常被忽略的優化重點,值得反覆咀嚼。

一、Gallery 載入大量圖片導致 OutOfMemoryError

當 Gallery 控件一次載入過多、過大的圖片時,極易觸發 OutOfMemoryError,也就是所謂的記憶體溢出。原因在於 Android 早期版本為每個應用分配的堆記憶體僅有數 MB,而 JPG 這類壓縮格式一旦在記憶體中完整展開,佔用的空間會成倍增長。透過 BitmapFactory.Options 的 inSampleSize 進行降採樣,是相當有效的解法:

  1. ImageView i = new ImageView(mContext);  
  2.           BitmapFactory.Options options=new BitmapFactory.Options();  
  3.           options.inSampleSize = 10;  
  4.           //貌似這個options的功能是返回縮略圖,10即表示長和寬為原來的1/10,即面積為原來的1/100  
  5.           //縮略圖可以減少內存占用  
  6.           Bitmap bm = BitmapFactory.decodeFile(lis.  
  7.                                    get(position).toString(),options);  
  8.           i.setImageBitmap(bm);  
  9.           bm.recycle();  
  10.           //資源回收 

設定 inSampleSize 為 10,代表取樣後的長寬各為原圖的十分之一、面積僅剩百分之一,記憶體負擔自然大幅降低;用完再呼叫 recycle() 主動釋放,避免資源滯留。

二、統一管理位圖資源並適時釋放

若應用中圖片眾多,建議以 WeakHashMap 搭配 WeakReference 集中管理,讓系统在記憶體吃緊時能自動回收不再被強引用的物件,並在需要時統一釋放:

  1. class ImageManager {     
  2.     private WeakHashMap<Integer, WeakReference<Bitmap>> mBitmaps;     
  3.     private WeakHashMap<Integer, WeakReference<Drawable》> mDrawables;     
  4.     
  5.     private boolean mActive = true;     
  6.     
  7.     public ImageManager() {     
  8.         mBitmaps = new WeakHashMap<Integer, WeakReference<Bitmap>>();     
  9.         mDrawables = new WeakHashMap<Integer, WeakReference<Drawable>>();     
  10.     }     
  11.     
  12.    
  13.     public Bitmap getBitmap(int resource) {     
  14.         if (mActive) {     
  15.             if (!mBitmaps.containsKey(resource)) {     
  16.                 mBitmaps.put(resource,     
  17.                     new WeakReference<Bitmap>(BitmapFactory.decodeResource(MainActivity.getContext().getResources(), resource)));     
  18.             }     
  19.             return ((WeakReference<Bitmap>)mBitmaps.get(resource)).get();     
  20.         }     
  21.         return null;     
  22.     }     
  23.     
  24.     public Drawable getDrawable(int resource) {     
  25.         if (mActive) {     
  26.             if (!mDrawables.containsKey(resource)) {     
  27.                 mDrawables.put(resource, new WeakReference<Drawable>(getApplication().getResources().getDrawable(resource)));     
  28.             }     
  29.             return ((WeakReference<Drawable>)mDrawables.get(resource)).get();     
  30.         }     
  31.         return null;     
  32.     }     
  33.     
  34.     public void recycleBitmaps() {     
  35.         Iterator itr = mBitmaps.entrySet().iterator();     
  36.         while (itr.hasNext()) {     
  37.             Map.Entry e = (Map.Entry)itr.next();     
  38.             ((WeakReference<Bitmap>) e.getValue()).get().recycle();     
  39.         }     
  40.         mBitmaps.clear();     
  41.     }     
  42.     
  43.     public ImageManager setActive(boolean b) {     
  44.         mActive = b;     
  45.         return this;     
  46.     }     
  47.     
  48.     public boolean isActive() {     
  49.         return mActive;     
  50.     }     
  51. }   

三、先檢查網路連線,避免無謂耗電

網路連線是耗電大戶。在需要連網的功能中,最好先確認連線狀態;若根本沒有網路,就直接跳過相關流程,省下電量也省下等待:

  1. private boolean isConnected(){  
  2.         ConnectivityManager mConnectivity = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);    
  3.         TelephonyManager mTelephony = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);  
  4.           
  5.         // 檢查網絡連接,如果無網絡可用,就不需要進行連網操作等  
  6.         NetworkInfo info = mConnectivity.getActiveNetworkInfo();  
  7.         if (info == null ||  
  8.                 !mConnectivity.getBackgroundDataSetting()) {  
  9.                 return false;  
  10.             }  
  11.         //判斷網絡連接類型,只有在3G或wifi裡進行一些數據更新。  
  12.         int netType = info.getType();  
  13.         int netSubtype = info.getSubtype();  
  14.         if (netType == ConnectivityManager.TYPE_WIFI) {  
  15.             return info.isConnected();  
  16.            } else if (netType == ConnectivityManager.TYPE_MOBILE  
  17.                 && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS  
  18.                 && !mTelephony.isNetworkRoaming()) {  
  19.             return info.isConnected();  
  20.            } else {  
  21.             return false;  
  22.         }  
  23.     } 

四、聰明選擇資料傳輸與解析方式

網路傳輸本身極度消耗資源,其中「傳輸方式」與「解析方式」都是優化重點。就解析而言,Tree Parse(DOM)會先把整份文件讀完,再依節點層次重新組裝;而 Event/Stream(SAX)則是邊讀邊解析,讀完的同時解析也告一段落,效率明顯更高。至於資料格式,JSON 與 Protobuf 的表現遠勝 XML。結論很清楚:行動裝置上應優先採用 SAX 這類串流解析,並盡量選用 JSON 等輕量級格式。

五、傳輸資料先壓縮

目前大多數網站都支援 GZIP 壓縮,下載大檔案時善用它能有效節省流量:

  1. HttpGet request =  
  2.         new HttpGet("https://example.com/gzipcontent");  
  3.     HttpResponse resp =  
  4.         new DefaultHttpClient().execute(request);  
  5.     HttpEntity entity = response.getEntity();  
  6.     InputStream compressed = entity.getContent();  
  7.     InputStream rawData = new GZIPInputStream(compressed); 

六、用 AlarmManager 有效管理背景服務

背景 Service 就像一個持續運轉的 Activity。若讓它不停輪詢伺服器、閒置時又 sleep,會非常耗電。更聰明的做法是用 AlarmManager 定時喚醒服務,例如每 30 分鐘執行一次:

  1. AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);  
  2.         Intent intent = new Intent(context, MyService.class);  
  3.         PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);  
  4.         long interval = DateUtils.MINUTE_IN_MILLIS * 30;  
  5.         long firstWake = System.currentTimeMillis() + interval;  
  6.         am.setRepeating(AlarmManager.RTC,firstWake, interval, pendingIntent); 

手機的整體效能與續航本就有其限制,這些看似瑣碎的優化細節,累積起來卻能對軟體品質產生本質性的影響,值得在開發過程中持續關注與積累。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved