Android開發(fā)筆記之:消息循環(huán)與Looper的詳解
Looper是用于給一個線程添加一個消息隊列(MessageQueue),并且循環(huán)等待,當有消息時會喚起線程來處理消息的一個工具,直到線程結(jié)束為止。通常情況下不會用到Looper,因為對于Activity,Service等系統(tǒng)組件,F(xiàn)rameworks已經(jīng)為我們初始化好了線程(俗稱的UI線程或主線程),在其內(nèi)含有一個Looper,和由Looper創(chuàng)建的消息隊列,所以主線程會一直運行,處理用戶事件,直到某些事件(BACK)退出。
如果,我們需要新建一個線程,并且這個線程要能夠循環(huán)處理其他線程發(fā)來的消息事件,或者需要長期與其他線程進行復(fù)雜的交互,這時就需要用到Looper來給線程建立消息隊列。
使用Looper也非常的簡單,它的方法比較少,最主要的有四個:
public static prepare();
public static myLooper();
public static loop();
public void quit();
使用方法如下:
1. 在每個線程的run()方法中的最開始調(diào)用Looper.prepare(),這是為線程初始化消息隊列。
2. 之后調(diào)用Looper.myLooper()獲取此Looper對象的引用。這不是必須的,但是如果你需要保存Looper對象的話,一定要在prepare()之后,否則調(diào)用在此對象上的方法不一定有效果,如looper.quit()就不會退出。
3. 在run()方法中添加Handler來處理消息
4. 添加Looper.loop()調(diào)用,這是讓線程的消息隊列開始運行,可以接收消息了。
5. 在想要退出消息循環(huán)時,調(diào)用Looper.quit()注意,這個方法是要在對象上面調(diào)用,很明顯,用對象的意思就是要退出具體哪個Looper。如果run()中無其他操作,線程也將終止運行。
下面來看一個實例
實例
這個例子實現(xiàn)了一個執(zhí)行任務(wù)的服務(wù):
public class LooperDemoActivity extends Activity {
private WorkerThread mWorkerThread;
private TextView mStatusLine;
private Handler mMainHandler;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.looper_demo_activity);
mMainHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
String text = (String) msg.obj;
if (TextUtils.isEmpty(text)) {
return;
}
mStatusLine.setText(text);
}
};
mWorkerThread = new WorkerThread();
final Button action = (Button) findViewById(R.id.looper_demo_action);
action.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mWorkerThread.executeTask("please do me a favor");
}
});
final Button end = (Button) findViewById(R.id.looper_demo_quit);
end.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mWorkerThread.exit();
}
});
mStatusLine = (TextView) findViewById(R.id.looper_demo_displayer);
mStatusLine.setText("Press 'do me a favor' to execute a task, press 'end of service' to stop looper thread");
}
@Override
public void onDestroy() {
super.onDestroy();
mWorkerThread.exit();
mWorkerThread = null;
}
private class WorkerThread extends Thread {
protected static final String TAG = "WorkerThread";
private Handler mHandler;
private Looper mLooper;
public WorkerThread() {
start();
}
public void run() {
// Attention: if you obtain looper before Looper#prepare(), you can still use the looper
// to process message even after you call Looper#quit(), which means the looper does not
//really quit.
Looper.prepare();
// So we should call Looper#myLooper() after Looper#prepare(). Anyway, we should put all stuff between Looper#prepare()
// and Looper#loop().
// In this case, you will receive "Handler{4051e4a0} sending message to a Handler on a dead thread
// 05-09 08:37:52.118: W/MessageQueue(436): java.lang.RuntimeException: Handler{4051e4a0} sending message
// to a Handler on a dead thread", when try to send a message to a looper which Looper#quit() had called,
// because the thread attaching the Looper and Handler dies once Looper#quit() gets called.
mLooper = Looper.myLooper();
// either new Handler() and new Handler(mLooper) will work
mHandler = new Handler(mLooper) {
@Override
public void handleMessage(Message msg) {
/*
* Attention: object Message is not reusable, you must obtain a new one for each time you want to use it.
* Otherwise you got "android.util.AndroidRuntimeException: { what=1000 when=-15ms obj=it is my please
* to serve you, please be patient to wait!........ } This message is already in use."
*/
// Message newMsg = Message.obtain();
StringBuilder sb = new StringBuilder();
sb.append("it is my please to serve you, please be patient to wait!\n");
Log.e(TAG, "workerthread, it is my please to serve you, please be patient to wait!");
for (int i = 1; i < 100; i++) {
sb.append(".");
Message newMsg = Message.obtain();
newMsg.obj = sb.toString();
mMainHandler.sendMessage(newMsg);
Log.e(TAG, "workthread, working" + sb.toString());
SystemClock.sleep(100);
}
Log.e(TAG, "workerthread, your work is done.");
sb.append("\nyour work is done");
Message newMsg = Message.obtain();
newMsg.obj = sb.toString();
mMainHandler.sendMessage(newMsg);
}
};
Looper.loop();
}
public void exit() {
if (mLooper != null) {
mLooper.quit();
mLooper = null;
}
}
// This method returns immediately, it just push an Message into Thread's MessageQueue.
// You can also call this method continuously, the task will be executed one by one in the
// order of which they are pushed into MessageQueue(they are called).
public void executeTask(String text) {
if (mLooper == null || mHandler == null) {
Message msg = Message.obtain();
msg.obj = "Sorry man, it is out of service";
mMainHandler.sendMessage(msg);
return;
}
Message msg = Message.obtain();
msg.obj = text;
mHandler.sendMessage(msg);
}
}
}
這個實例中,主線程中執(zhí)行任務(wù)僅是給服務(wù)線程發(fā)一個消息同時把相關(guān)數(shù)據(jù)傳過去,數(shù)據(jù)會打包成消息對象(Message),然后放到服務(wù)線程的消息隊列中,主線程的調(diào)用返回,此過程很快,所以不會阻塞主線程。服務(wù)線程每當有消息進入消息隊列后就會被喚醒從隊列中取出消息,然后執(zhí)行任務(wù)。服務(wù)線程可以接收任意數(shù)量的任務(wù),也即主線程可以不停的發(fā)送消息給服務(wù)線程,這些消息都會被放進消息隊列中,服務(wù)線程會一個接著一個的執(zhí)行它們----直到所有的任務(wù)都完成(消息隊列為空,已無其他消息),服務(wù)線程會再次進入休眠狀態(tài)----直到有新的消息到來。
如果想要終止服務(wù)線程,在mLooper對象上調(diào)用quit(),就會退出消息循環(huán),因為線程無其他操作,所以整個線程也會終止。
需要注意的是當一個線程的消息循環(huán)已經(jīng)退出后,不能再給其發(fā)送消息,否則會有異常拋出"RuntimeException: Handler{4051e4a0} sending message to a Handler on a dead thread"。所以,建議在Looper.prepare()后,調(diào)用Looper.myLooper()來獲取對此Looper的引用,一來是用于終止(quit()必須在對象上面調(diào)用); 另外就是用于接收消息時檢查消息循環(huán)是否已經(jīng)退出(如上例)。
相關(guān)文章
Android穩(wěn)定性:可遠程配置化的Looper兜底框架
這篇文章主要為大家介紹了Android穩(wěn)定性可遠程配置化的Looper兜底框架實例實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02Android開發(fā)筆記SQLite優(yōu)化記住密碼功能
這篇文章主要為大家詳細介紹了Android開發(fā)筆記SQLite優(yōu)化記住密碼功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07Android中Rxjava實現(xiàn)三級緩存的兩種方式
這篇文章主要介紹了Android中Rxjava實現(xiàn)三級緩存的兩種方式,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-04-04Android 多線程實現(xiàn)重復(fù)啟動與停止的服務(wù)
這篇文章主要介紹了Android 多線程實現(xiàn)重復(fù)啟動與停止的服務(wù)的相關(guān)資料,多線程環(huán)境下為了避免死鎖,一般提倡開放調(diào)用,開放調(diào)用可以避免死鎖,它的代價是失去原子性,這里說明重復(fù)啟動與停止的服務(wù),需要的朋友可以參考下2017-08-08Android編程實現(xiàn)兩個Activity相互切換而不使用onCreate()的方法
這篇文章主要介紹了Android編程實現(xiàn)兩個Activity相互切換而不使用onCreate()的方法,結(jié)合實例形式分析了多個Activity切換而不重新創(chuàng)建的操作技巧,需要的朋友可以參考下2017-01-01Android報錯Error:Could not find com.android.tools.build:gradle
這篇文章主要介紹了Android Studio報錯Error:Could not find com.android.tools.build:gradle:4.1解決辦法,碰到該問題的同學快過來看看吧2021-08-08Android ViewPager無限循環(huán)滑動并可自動滾動完整實例
對于Android ViewPager廣告頁可無限循環(huán)滑動并可自動滾動帶有小圓點的這個功能很多APP都有這個功能,這里為大家提供了完整的實例代碼2018-03-03Android中EditText和AutoCompleteTextView設(shè)置文字選中顏色方法
這篇文章主要介紹了Android中EditText和AutoCompleteTextView設(shè)置文字選中顏色方法,本文給出了效果圖和實現(xiàn)代碼,需要的朋友可以參考下2015-01-01Android?RecyclerLineChart實現(xiàn)圖表繪制教程
這篇文章主要為大家介紹了Android?RecyclerLineChart實現(xiàn)圖表繪制教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12