6

I am having a problem with Android looper. I have a class that has extended AsynTask. Inside doInBackground() method i have Looper.prepare() and some code below.

It runs well and good for the first time but after that it gives an exception " Only one Looper may be created per thread" .

There seems some solution to use Looper.quit() but i am unable to implement it.

Any help will be appreciated.

viv
  • 6,158
  • 6
  • 39
  • 54
  • 1
    It does seem to me that Looper.quit() is what you needed here. In android API documentation, it is clearly stated that "Be sure to call loop() after calling this method, and end it by calling quit()". – onlygo Oct 08 '10 at 07:39
  • What do you mean by "am unable to implement it."? – methode Oct 08 '10 at 07:49
  • I mean that i am not able to find quit() inside Looper. It shows getMainLooper, myLooper(), loop(), myQueue(), prepare(), prepareMainLooper() but not quit(). – viv Oct 08 '10 at 07:58

4 Answers4

3
class LooperThread extends Thread {
      public Handler mHandler;

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

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }
Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242
qjbagu
  • 31
  • 2
0
getActivity().runOnUiThread (new Thread(new Runnable() { 
    public void run() {
        Looper.myLooper();
        getActivity().invalidateOptionsMenu();
    }
}));
Michael Assraf
  • 111
  • 2
  • 3
0

Just add the following check.

 if (Looper.myLooper() == null)
     Looper.prepare();
Aown Raza
  • 2,023
  • 13
  • 29
  • http://stackoverflow.com/questions/23038682/java-lang-runtimeexception-only-one-looper-may-be-created-per-thread/24115631#24115631 – Aown Raza Sep 01 '15 at 12:01
0

Try...

Looper.getMainLooper().quit();
sasykes
  • 66
  • 5