0
votes

I have a thread:

public class KelvinThread implements Runnable {

private Handler mSoundHandler;

public KelvinThread() {
    super();
    mSoundHandler = new Handler();
}

private Runnable mSoundThread = new Runnable() {
    public void run() {
        // my treatment
    }
};

@Override
public void run() {
    while (true) {
        // ....
        mSoundHandler.postDelayed(mSoundThread, 2000);
        // ....
    }
}

This thread "KelvinThread" is created and started from another Thread.

I have this error:

Can't create handler inside thread that has not called Looper.prepare()

when my handler is allocated : mSoundHandler = new Handler();

Thank you for your help guys !

1
In seven hells why you are mixing Handler with native Thread? I think this is very ungly solution and you shouldn't do it - it seems like bad application logic design. - Simon Dorociak
It is not really. Sometimes you have to do it, for example to trigger UI changes from thread or may other cases. Really depends. - Volodymyr Lykhonis
Hi Ragnar, I read your advice. But how can I do a trigger without Handler ? Is there another way to do that ? - anthony

1 Answers

0
votes

Please refer to Looper documentation. There is also example.

UPD You might also be able to use Looper.getMainLooper() to attach handler to main looper instead of creating thread one.