I have a class
which extends to Thread
as follows -
public class ThreadTest extends Thread {
private Handler handler;
private Runnable runnable;
public ThreadTest(Runnable runnable, Handler handler) {
this.handler = handler;
this.runnable = runnable;
}
@Override
public void run() {
super.run();
Message msg = handler.obtainMessage();
msg.obj = "YUSSSSSS!";
handler.sendMessage(msg);
if (Looper.myLooper() != null) {
Looper.myLooper().quit();
Log.i("Looper", "has been quit");
}
}
}
Now, I wish to attach a looper
to this thread. From my understanding of Looper
only the main thread gets a looper
attached to it by default.
I try to call Looper.prepare()
and Looper.loop()
form the constructor of the ThreadTest
class like this -
public ThreadTest(Runnable runnable, Handler handler) {
Looper.prepare();
this.handler = handler;
this.runnable = runnable;
Looper.loop();
}
But, I get java.lang.RuntimeException: Only one Looper may be created per thread
exception at Looper.prepare();
.
While, if I attach the looper
in Run()
, I don't face any problem whatsoever.
What am I doing wrong?