0

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();
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Mr Hoelee
  • 446
  • 2
  • 7
  • 24
  • what actually do you want to achieve? why not to use `HandlerThread`? – pskink Oct 22 '17 at 10:25
  • I like to perform some repeat checking whenever application is running. It this possible? – Mr Hoelee Oct 22 '17 at 10:27
  • Yes. It's possible with HandlerThread. Check for this post for example: https://stackoverflow.com/questions/3134683/android-toast-in-a-thread/45922317#45922317 – Ravindra babu Oct 31 '17 at 15:57

0 Answers0