編輯:關於 Android 程式設計
App 寫完、老化測試也跑完,資料收發都正常,看似可以收工。但丟一句 adb shell top -m 5 之後會發現:自己的 App 佔的 CPU 居然最高。
寫出一個能跑的 App 不難,難的是願不願意認真分析它的記憶體與運算佔用、預防 OOM 與各種偶發問題。這些知識門檻不高,但養成習慣之後,能省下後續大量除錯時間。下面就把整個排查過程走一遍。

com.digissin.twelve 這個測試行程一直排第一位。帶著「是不是主/子執行緒做了耗時操作、網路請求,或者 new 了太多物件」的疑問,打開 DDMS 分析。

定位到 RSUDPProtocol & PostBytesThread 第 134 行:

問題出在一個空轉的 while 迴圈。這個迴圈不能拿掉——App 必須持續和後端保持通信。流程是:有資料送來時 isPause 被設為 true,迴圈裡發完一包後設回 false,於是又進入了「什麼都不做、但頻率極高地空轉」的狀態。
直覺做法是丟個 sleep() 進去。但這裡行不通:App 的需求是隨時能接收主執行緒派發的協定封包,一旦 sleep,執行緒就完全不幹活了,後續的封包發送也就失去意義。
換個角度想:isPause 為 false 時根本不需要子執行緒工作,那就讓它休眠;等主執行緒派發資料過來再把它叫起來。這正是 wait() 與 notify() 的場景。
這裡有個關鍵觀念要先釐清:Thread 與 Object 上的 wait()/notify() 並不相同。直接在 Thread 上呼叫這兩個方法是不會作用的,必須建立一個 Object 作為「管理者」。
打個比方:子執行緒是基層員工,那個 Object 就是管理者。員工即使知道自己下一步要做什麼,也得管理者點頭才能動;否則整個管理秩序會亂掉。所以我們用一個帶 synchronized 的內部類別物件來統一控制子執行緒的暫停與恢復。
private static PostBytesThread mThreadInstance = null;
public synchronized static PostBytesThread getThreadInstance() {
if (mThreadInstance == null) {
mThreadInstance = new PostBytesThread();
}
return mThreadInstance;
}
public synchronized boolean isPause() { return isPause; }
public synchronized void setPause(boolean isPause) { this.isPause = isPause; }
public byte[] getPost_bytes() { return post_bytes; }
public void setPost_bytes(byte[] post_bytes) { this.post_bytes = post_bytes; }
public synchronized void onThreadPause() {
try {
Log.e(TAG, TAG + " onThreadPause() ----");
this.wait();
} catch (InterruptedException e) {
Log.i(TAG, e.toString());
}
}
public synchronized void onThreadResume() {
Log.e(TAG, TAG + " onThreadResume() ----");
this.notify();
}
@Override
public void run() {
if (udpSocket == null) {
Log.i(TAG, TAG + " udpSocket is null");
return;
}
while (true) {
Log.i(TAG, TAG + " isPause() state:" + isPause());
if (isPause()) {
try {
sendPacket.setData(getPost_bytes());
sendPacket.setLength(getPost_bytes().length);
sendPacket.setAddress(serverAddress);
sendPacket.setPort(DEFAULT_POTR);
udpSocket.send(sendPacket);
Thread.sleep(1000);
setPause(false);
} catch (InterruptedException e) {
Log.i(TAG, "Exception:" + e.toString());
} catch (IOException e) {
Log.i(TAG, "Exception:" + e.toString());
}
} else {
onThreadPause();
}
}
}
呼叫端收到主執行緒派發的協定封包時,把它喚醒並設定資料:
public void setPostBytesData(byte[] data) {
PostBytesThread.getThreadInstance().start();
PostBytesThread.getThreadInstance().onThreadResume();
PostBytesThread.getThreadInstance().setPause(true);
PostBytesThread.getThreadInstance().setPost_bytes(data);
boolean isPause = PostBytesThread.getThreadInstance().isPause();
Log.d("PostBytesThread", "PostBytesThread isPause() state:" + isPause);
}
改完之後再看一次:

CPU 佔用大幅下降,目標達成。
更新進度條、上傳下載時,我們常需要從子執行緒向 Handler 送 Message。這裡最容易犯的錯,就是在迴圈裡不停地 new 新物件。
@Override
public void run() {
while (true) {
try {
SettingLocationTime();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void SettingLocationTime() throws InterruptedException {
if (handler != null) {
SendMessage(post_data);
time = setting_time > 0 ? setting_time : default_time;
Thread.sleep(time * 1000);
}
}
/**
* 這個函數在 while(true) 裡被反覆呼叫
* Message 與 Bundle 會被不斷建立新的實例 —— 這是致命的低級錯誤
*/
private void SendMessage(byte[] data) {
byte[] _data = ByteParseBeanTools.PostProtocolByte(
ByteProtocolSessionType.LOCATION_STATE_SEND, data);
Message msg = new Message(); // 不必要的 Message 新實例
msg.what = MainSessionUtil.SEND_POST_BYETS_DATA;
Bundle bundle = new Bundle(); // 不必要的 Bundle 新實例
bundle.putByteArray(MainSessionUtil.BYTES_DATA_KEY, _data);
msg.setData(bundle);
handler.sendMessage(msg);
}
兩個重點:Bundle 重複使用,Message 從 MessagePool 拿。
/**
* Bundle 可以在類別建立時就實例化一次,等於一個鐵碗
* 每次換掉碗裡的水(clear 之後重新填),就不必反覆開新的記憶體空間
*
* Message 更省事:直接呼叫 Handler 的 obtainMessage()
* 這個物件隨 Handler 建立而存在、隨 Handler 消亡而回收,不需自己 new
* obtainMessage() 的物件來自 MessagePool
*/
private void SendMessage(byte[] data) {
bundle.clear(); // 倒掉舊水
byte[] _data = ByteParseBeanTools.PostProtocolByte(
ByteProtocolSessionType.LOCATION_STATE_SEND, data);
Message msg = handler.obtainMessage();
msg.what = MainSessionUtil.SEND_POST_BYETS_DATA;
bundle.putByteArray(MainSessionUtil.BYTES_DATA_KEY, _data); // 裝新水
msg.setData(bundle);
handler.sendMessage(msg);
}
兩個改動合起來,CPU 佔用明顯下降,問題也就跟著解決了。這類優化單看都不起眼,但在高頻迴圈裡,差距會被放大得非常清楚。
Android View 繪製與螢幕顯示原理解析
顯示流程概覽 Android 應用畫面顯示可概括為:應用將測量、布局與繪製後的 Surface 交給 SurfaceFlinger,再由系統渲染到螢幕。SurfaceFl
Volley 學習(五):以 HttpUrlConnection 與 Volley 實作頭像上傳
頭像上傳的核心概念 無論使用哪種網路工具,頭像上傳的本質都是把圖片轉成可傳輸的資料。常見做法是將 Bitmap 壓縮為 byte 陣列,再用 Base64 編碼成字串,最
BaseAdapter 使用筆記:getView 的三種寫法與 ViewHolder 優化
適配器模式的應用價值在於兩點:1. 降低程式耦合性2. 容易擴展ListView 的顯示與緩存機制可以一句話概括:需要時才顯示,顯示完就進入緩存。而 BaseAdapte
Android 自定義圖形單點移動與縮放效果
單點拖曳在單指操作時,可透過 MotionEvent 取得目前座標,並更新檢視的 LayoutParams 邊距,讓圖形跟著手指移動。這種方式適合需要直接操控位置的簡單互