編輯:Android 開發實例
行動裝置的運算資源與電力始終有限,一段看似不起眼的小疏忽,往往會在實際環境中放大成災難。以下整理了六個在 Android 開發中極具代表性、卻又常被忽略的優化重點,值得反覆咀嚼。
當 Gallery 控件一次載入過多、過大的圖片時,極易觸發 OutOfMemoryError,也就是所謂的記憶體溢出。原因在於 Android 早期版本為每個應用分配的堆記憶體僅有數 MB,而 JPG 這類壓縮格式一旦在記憶體中完整展開,佔用的空間會成倍增長。透過 BitmapFactory.Options 的 inSampleSize 進行降採樣,是相當有效的解法:
- ImageView i = new ImageView(mContext);
- BitmapFactory.Options options=new BitmapFactory.Options();
- options.inSampleSize = 10;
- //貌似這個options的功能是返回縮略圖,10即表示長和寬為原來的1/10,即面積為原來的1/100
- //縮略圖可以減少內存占用
- Bitmap bm = BitmapFactory.decodeFile(lis.
- get(position).toString(),options);
- i.setImageBitmap(bm);
- bm.recycle();
- //資源回收
設定 inSampleSize 為 10,代表取樣後的長寬各為原圖的十分之一、面積僅剩百分之一,記憶體負擔自然大幅降低;用完再呼叫 recycle() 主動釋放,避免資源滯留。
若應用中圖片眾多,建議以 WeakHashMap 搭配 WeakReference 集中管理,讓系统在記憶體吃緊時能自動回收不再被強引用的物件,並在需要時統一釋放:
- class ImageManager {
- private WeakHashMap<Integer, WeakReference<Bitmap>> mBitmaps;
- private WeakHashMap<Integer, WeakReference<Drawable》> mDrawables;
- private boolean mActive = true;
- public ImageManager() {
- mBitmaps = new WeakHashMap<Integer, WeakReference<Bitmap>>();
- mDrawables = new WeakHashMap<Integer, WeakReference<Drawable>>();
- }
- public Bitmap getBitmap(int resource) {
- if (mActive) {
- if (!mBitmaps.containsKey(resource)) {
- mBitmaps.put(resource,
- new WeakReference<Bitmap>(BitmapFactory.decodeResource(MainActivity.getContext().getResources(), resource)));
- }
- return ((WeakReference<Bitmap>)mBitmaps.get(resource)).get();
- }
- return null;
- }
- public Drawable getDrawable(int resource) {
- if (mActive) {
- if (!mDrawables.containsKey(resource)) {
- mDrawables.put(resource, new WeakReference<Drawable>(getApplication().getResources().getDrawable(resource)));
- }
- return ((WeakReference<Drawable>)mDrawables.get(resource)).get();
- }
- return null;
- }
- public void recycleBitmaps() {
- Iterator itr = mBitmaps.entrySet().iterator();
- while (itr.hasNext()) {
- Map.Entry e = (Map.Entry)itr.next();
- ((WeakReference<Bitmap>) e.getValue()).get().recycle();
- }
- mBitmaps.clear();
- }
- public ImageManager setActive(boolean b) {
- mActive = b;
- return this;
- }
- public boolean isActive() {
- return mActive;
- }
- }
網路連線是耗電大戶。在需要連網的功能中,最好先確認連線狀態;若根本沒有網路,就直接跳過相關流程,省下電量也省下等待:
- private boolean isConnected(){
- ConnectivityManager mConnectivity = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
- TelephonyManager mTelephony = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
- // 檢查網絡連接,如果無網絡可用,就不需要進行連網操作等
- NetworkInfo info = mConnectivity.getActiveNetworkInfo();
- if (info == null ||
- !mConnectivity.getBackgroundDataSetting()) {
- return false;
- }
- //判斷網絡連接類型,只有在3G或wifi裡進行一些數據更新。
- int netType = info.getType();
- int netSubtype = info.getSubtype();
- if (netType == ConnectivityManager.TYPE_WIFI) {
- return info.isConnected();
- } else if (netType == ConnectivityManager.TYPE_MOBILE
- && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS
- && !mTelephony.isNetworkRoaming()) {
- return info.isConnected();
- } else {
- return false;
- }
- }
網路傳輸本身極度消耗資源,其中「傳輸方式」與「解析方式」都是優化重點。就解析而言,Tree Parse(DOM)會先把整份文件讀完,再依節點層次重新組裝;而 Event/Stream(SAX)則是邊讀邊解析,讀完的同時解析也告一段落,效率明顯更高。至於資料格式,JSON 與 Protobuf 的表現遠勝 XML。結論很清楚:行動裝置上應優先採用 SAX 這類串流解析,並盡量選用 JSON 等輕量級格式。
目前大多數網站都支援 GZIP 壓縮,下載大檔案時善用它能有效節省流量:
- HttpGet request =
- new HttpGet("https://example.com/gzipcontent");
- HttpResponse resp =
- new DefaultHttpClient().execute(request);
- HttpEntity entity = response.getEntity();
- InputStream compressed = entity.getContent();
- InputStream rawData = new GZIPInputStream(compressed);
背景 Service 就像一個持續運轉的 Activity。若讓它不停輪詢伺服器、閒置時又 sleep,會非常耗電。更聰明的做法是用 AlarmManager 定時喚醒服務,例如每 30 分鐘執行一次:
- AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
- Intent intent = new Intent(context, MyService.class);
- PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
- long interval = DateUtils.MINUTE_IN_MILLIS * 30;
- long firstWake = System.currentTimeMillis() + interval;
- am.setRepeating(AlarmManager.RTC,firstWake, interval, pendingIntent);
手機的整體效能與續航本就有其限制,這些看似瑣碎的優化細節,累積起來卻能對軟體品質產生本質性的影響,值得在開發過程中持續關注與積累。
Android 如何解析 JSON:從 API 回傳資料中取出欄位值
JSON 的全名是 JavaScript Object Notation,是一種與程式語言無關的資料交換格式。相較於 XML,它沒有冗長的標籤,結構清楚、體積更小,解析速
Android JSON 資料解析:JSONObject 與天氣資訊抓取
在 Android 開發中,JSON 解析幾乎是網路應用的必備技能。無論是氣象、新聞、社群或商品資料,後端常會以 JSON 格式回傳結果。本文說明如何從 JSON 中取出
Android 為 WebView 加上頂部進度條的實作
寫這篇純粹做備忘,示範一個在 WebView 上方顯示載入進度條的簡易寫法。 效果如下: 版面配置 由上到下依序是:重新載入按鈕、進度條、WebView。用 Rela
Android 登入介面設計與安全性防呆
登入畫面看似只是兩個輸入框加一顆按鈕,但它同時承担了使用者體驗與安全防線兩個角色。做得好,使用者一眼就知道怎麼填;做得馬虎,帳號被暴力破解也只是時間問題。 本文會把版面