Home » Android » Looper thread not repeating itself

Looper thread not repeating itself

Posted by: admin November 1, 2017 Leave a comment

Questions:

I want to create another thread to loop itself and perform something.
May I know any mistake I done? Because it just perform single time and stop.

public class LooperClazz extends Thread {
private MessageQueue messageQueue;
private Context context;
private long counter = 0;

public LooperClazz(Context context){
    this.context = context;
}

@Override
public void run() {
    Looper.prepare();
    long threadId1 = Thread.currentThread().getId(); //new thread

    final Handler responseHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            long mainThreadId = Thread.currentThread().getId(); //1
            //Here success to Toast something.
        }
    };

    messageQueue = Looper.myQueue();
    messageQueue.addIdleHandler(new MessageQueue.IdleHandler() {
        @Override
        public boolean queueIdle() {
            //I'm expecting running this in a loop, but it not, why?
            long threadId2 = Thread.currentThread().getId();
            //Same as threadId1 
            counter++;
            Message msg = new Message();
            msg.obj = counter+ "";
            responseHandler.sendMessage(msg);
            SystemClock.sleep(3000);
            return true;
        }
    });
    Looper.loop();
}
}

In MyApplication, I just start it with

new LooperClazz(context).start();
Answers: