我创建了一个Looper 线程类:
public class MyLooperThread extends Thread{
private Handler mHandler;
public void init(){
start(); //start the thread
synchronized (this) {
wait(5000); //wait for run()
}
Log.d("DEBUG","Init Done!");
//EXCEPTION: Can't create handler inside thread that has not called Looper.prepare()
MyObject obj = new MyObject(mHandler);
}
@Override
public void run() {
Looper.prepare();
mHandler = new Handler(){
@Override
public void handleMessage(Message msg){
//Check installed app package names, NOTHING RELATED WITH UI ...
}
};
synchronized (this) {
notify();
}
Looper.loop();
}//end of run()
}
在我的Activity中,我调用了上面MyLooperThread
的init()
方法onCreate()
。此外,我有一个ToggleButton
元素,当ToggleButton
被检查时,我也调用MyLooperThread
'sinit()
方法。
public class MyActivity extends Activity implements OnCheckedChangeListener{
…
@Override
protected void onCreate(Bundle savedInstanceState){
…
myToggleButton.setOnCheckedChangeListener(this);
myToggleButton.setChecked(true);//checked by default
MyLooperThread myLooper = new MyLooperThread();
myLooper.init();
}
@Override
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
if(isChecked){
MyLooperThread myLooper = new MyLooperThread();
myLooper.init();
}else{
...
}
}
}
启动我的应用程序时,它很好。我的切换按钮默认显示为选中状态。当我取消选中并再次检查时,出现异常:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
指向init()
方法的最后一行代码MyObject obj = new MyObject(mHandler);
为什么我得到这个例外?我不明白,我mHandler
是在我调用之后创建Looper.prepare()
的run()
。