I created a Looper thread class:
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()
}
In my Activity, I call above MyLooperThread
's init()
method in onCreate()
. Besides, I have a ToggleButton
element, when ToggleButton
is checked, I call MyLooperThread
's init()
method too.
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{
...
}
}
}
When launch my app, it is fine. My toggle button is shown as checked by default. When I uncheck it & check it again, I got exception:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
which is pointed to the init()
method's last line of code MyObject obj = new MyObject(mHandler);
Why I got this exception? I don't understand, my mHandler
is created after I called Looper.prepare()
in run()
.