Looper.myLooper():
Return the Looper object associated with the current thread
即:获取当前进程的looper对象。
还有一个类似的 Looper.getMainLooper() 用于获取主线程的Looper对象。E/AndroidRuntime( 6173): Uncaught handler: thread Thread-8 exiting due to uncaught exception
E/AndroidRuntime( 6173): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
让Looper开始工作,从消息队列里取消息,处理消息。
问题代码:
private Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
InputMethodManager m = (InputMethodManager) editText
.getContext().getSystemService(
Context.INPUT_METHOD_SERVICE);
m.showSoftInput(editText, 0);
//
Looper.prepare();
Toast.makeText(Main.this, "show", Toast.LENGTH_LONG).show();
Looper.loop();
}
}, 1000);
}
}
E/AndroidRuntime( 1819): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
E/AndroidRuntime( 1819): at android.os.Handler.(Handler.java:121)
E/AndroidRuntime( 1819): at android.widget.Toast.(Toast.java:68)
E/AndroidRuntime( 1819): at android.widget.Toast.makeText(Toast.java:231)
Handler.java:121
119 mLooper = Looper.myLooper();
120 if (mLooper == null) {
121 throw new RuntimeException(
122 "Can't create handler inside thread that has not called Looper.prepare()");}
Toast.java:68 ——>成员变量,在初始化时会跟着初始化
68 final Handler mHandler = new Handler();
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();//******************
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();//*************
}
}
Toast.java 的第231行的代码是创建一个新的Toast实例,而实例化的过程中,就需要执行第68行,也就是声明并创建Handler(成员变量)的实例。那么来看Handler.java的第121行到底做了什么,如下所示:
119 mLooper = Looper.myLooper();
120 if (mLooper == null) {
121 throw new RuntimeException(
122 "Can't create handler inside thread that has not called Looper.prepare()");}
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static final Looper myLooper() {
return (Looper)sThreadLocal.get();
}
(6) Android官方文档中Looper的介绍:
Class used to run a message loop for a thread.
Threads by default do not have a message loop associated with them; to create one, call in the thread that is to run the loop, and then to have it process messages until the loop is stopped.
Most interaction with a message loop is through the class.
This is a typical example of the implementation of a Looper thread, using the separation of and to create an initial Handler to communicate with the Looper.
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
原文:http://jeff-pluto-1874.iteye.com/blog/869710