Hi I am trying to use a thread with a handler and a looper in Android.

Thread class:

public void run() {
    Looper.prepare();

    handler = new AndroidHandler(context);
    Looper.loop();

    while (!stopMe) {
                       someMethod();
               }
           ((Handler) handler).getLooper().quit();
 }

public void someMethod(){
  Log.i("New System", "Handling ");
    order ++;
    Message m=handler.obtainMessage();
    m.arg1=order;
    handler.sendMessage(m);
 }

in a separate class:

public class AndroidHandler extends Handler{
   public AndroidHandle(Context){
        super();
  }
   public void dispatchMessage(Message m) {
    super.dispatchMessage(m);

}
   @Override
public void handleMessage(Message msg) {

    Log.i("New System", "handling Message "+msg.arg1);
   }
 }

It doens't work!!! messages aren't being sent and nothing is getting printed in the console and I don't know how to fix it.... What is the problem here any ideas? thanks

ps: I don't want to use the ui thread I want to do this in a separate thread.

有帮助吗?

解决方案

That's because you are doing your infinite while loop in the same thread as the looper! So this thread is kept busy and cannot receive messages...

You need to let the Looper's thread on its own.

Let's say you setup your looper thread like this:

class LooperThread extends Thread {
  public Handler handler;

  public void run() {
      Looper.prepare();

      mHandler = new Handler() {
          public void handleMessage(Message msg) {
              Log.i("New System", "handling Message "+msg.arg1);
          }
      };

      Looper.loop();
  }
}

LooperThread looper = new LooperThread();
looper.start();

Then you can send messages from any OTHER thread (the UI thread or any other one) just the same way as you did:

Handler handler = looper.handler;
Message m = handler.obtainMessage();
m.arg1 = order;
handler.sendMessage(m);

But don't do this from the same thread as the looper or it doesn't make any sense.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top