Android开发笔记之:消息循环与Looper的详解
程序员文章站
2023-11-20 17:49:04
understanding looperlooper是用于给一个线程添加一个消息队列(messagequeue),并且循环等待,当有消息时会唤起线程来处理消息的一个工具,直...
understanding looper
looper是用于给一个线程添加一个消息队列(messagequeue),并且循环等待,当有消息时会唤起线程来处理消息的一个工具,直到线程结束为止。通常情况下不会用到looper,因为对于activity,service等系统组件,frameworks已经为我们初始化好了线程(俗称的ui线程或主线程),在其内含有一个looper,和由looper创建的消息队列,所以主线程会一直运行,处理用户事件,直到某些事件(back)退出。
如果,我们需要新建一个线程,并且这个线程要能够循环处理其他线程发来的消息事件,或者需要长期与其他线程进行复杂的交互,这时就需要用到looper来给线程建立消息队列。
使用looper也非常的简单,它的方法比较少,最主要的有四个:
public static prepare();
public static mylooper();
public static loop();
public void quit();
使用方法如下:
1. 在每个线程的run()方法中的最开始调用looper.prepare(),这是为线程初始化消息队列。
2. 之后调用looper.mylooper()获取此looper对象的引用。这不是必须的,但是如果你需要保存looper对象的话,一定要在prepare()之后,否则调用在此对象上的方法不一定有效果,如looper.quit()就不会退出。
3. 在run()方法中添加handler来处理消息
4. 添加looper.loop()调用,这是让线程的消息队列开始运行,可以接收消息了。
5. 在想要退出消息循环时,调用looper.quit()注意,这个方法是要在对象上面调用,很明显,用对象的意思就是要退出具体哪个looper。如果run()中无其他操作,线程也将终止运行。
下面来看一个实例
实例
这个例子实现了一个执行任务的服务:
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);
}
}
}
这个实例中,主线程中执行任务仅是给服务线程发一个消息同时把相关数据传过去,数据会打包成消息对象(message),然后放到服务线程的消息队列中,主线程的调用返回,此过程很快,所以不会阻塞主线程。服务线程每当有消息进入消息队列后就会被唤醒从队列中取出消息,然后执行任务。服务线程可以接收任意数量的任务,也即主线程可以不停的发送消息给服务线程,这些消息都会被放进消息队列中,服务线程会一个接着一个的执行它们----直到所有的任务都完成(消息队列为空,已无其他消息),服务线程会再次进入休眠状态----直到有新的消息到来。
如果想要终止服务线程,在mlooper对象上调用quit(),就会退出消息循环,因为线程无其他操作,所以整个线程也会终止。
需要注意的是当一个线程的消息循环已经退出后,不能再给其发送消息,否则会有异常抛出"runtimeexception: handler{4051e4a0} sending message to a handler on a dead thread"。所以,建议在looper.prepare()后,调用looper.mylooper()来获取对此looper的引用,一来是用于终止(quit()必须在对象上面调用); 另外就是用于接收消息时检查消息循环是否已经退出(如上例)。
looper是用于给一个线程添加一个消息队列(messagequeue),并且循环等待,当有消息时会唤起线程来处理消息的一个工具,直到线程结束为止。通常情况下不会用到looper,因为对于activity,service等系统组件,frameworks已经为我们初始化好了线程(俗称的ui线程或主线程),在其内含有一个looper,和由looper创建的消息队列,所以主线程会一直运行,处理用户事件,直到某些事件(back)退出。
如果,我们需要新建一个线程,并且这个线程要能够循环处理其他线程发来的消息事件,或者需要长期与其他线程进行复杂的交互,这时就需要用到looper来给线程建立消息队列。
使用looper也非常的简单,它的方法比较少,最主要的有四个:
public static prepare();
public static mylooper();
public static loop();
public void quit();
使用方法如下:
1. 在每个线程的run()方法中的最开始调用looper.prepare(),这是为线程初始化消息队列。
2. 之后调用looper.mylooper()获取此looper对象的引用。这不是必须的,但是如果你需要保存looper对象的话,一定要在prepare()之后,否则调用在此对象上的方法不一定有效果,如looper.quit()就不会退出。
3. 在run()方法中添加handler来处理消息
4. 添加looper.loop()调用,这是让线程的消息队列开始运行,可以接收消息了。
5. 在想要退出消息循环时,调用looper.quit()注意,这个方法是要在对象上面调用,很明显,用对象的意思就是要退出具体哪个looper。如果run()中无其他操作,线程也将终止运行。
下面来看一个实例
实例
这个例子实现了一个执行任务的服务:
复制代码 代码如下:
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);
}
}
}
这个实例中,主线程中执行任务仅是给服务线程发一个消息同时把相关数据传过去,数据会打包成消息对象(message),然后放到服务线程的消息队列中,主线程的调用返回,此过程很快,所以不会阻塞主线程。服务线程每当有消息进入消息队列后就会被唤醒从队列中取出消息,然后执行任务。服务线程可以接收任意数量的任务,也即主线程可以不停的发送消息给服务线程,这些消息都会被放进消息队列中,服务线程会一个接着一个的执行它们----直到所有的任务都完成(消息队列为空,已无其他消息),服务线程会再次进入休眠状态----直到有新的消息到来。
如果想要终止服务线程,在mlooper对象上调用quit(),就会退出消息循环,因为线程无其他操作,所以整个线程也会终止。
需要注意的是当一个线程的消息循环已经退出后,不能再给其发送消息,否则会有异常抛出"runtimeexception: handler{4051e4a0} sending message to a handler on a dead thread"。所以,建议在looper.prepare()后,调用looper.mylooper()来获取对此looper的引用,一来是用于终止(quit()必须在对象上面调用); 另外就是用于接收消息时检查消息循环是否已经退出(如上例)。