简体   繁体   中英

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

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 !

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM