0

doInBackground() works fine.. code after Looper.loop() will not work. Log not printing after Looper.Loop() and not executing onPostExceute(). I need to wait until method 1,2,3 execute. Exception will occure in method1 if Looper.prepare() not used.

@Override
    protected Void doInBackground(Void... params) {
        try {

                if (Looper.myLooper() == null)
                    Looper.prepare();               
                method1();
                method2();
                method3();
                Looper.loop();

                Log.d(TAG,"after loop()");
            } else {
                method4(); //inside asyn task
            }

            Log.d(TAG,"doInBackground end");

        }catch (Exception e) {
            Log.d(TAG,"doInBackground exception "+e);
        }


        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        try {


            Log.d(TAG, "onPostExecute");



            //............

        }catch (Exception e){
            Log.d(TAG,"onPostExecute end");
        }
    }


    @Override
    protected void onPreExecute() {
        //.....
    }
Akshay Kumar S
  • 333
  • 3
  • 12

1 Answers1

2

Looper.loop makes a thread loop forever waiting for incoming events on a message queue and running the associated runnables. It should never be called on an AsyncTask, it will cause the entire AsyncTask thread to infinitely loop, deadlocking all future AsyncTasks. It should only be called on Threads, and only if you understand how to use it.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • Is there any exception will occur if I'm not using Looper.loop() with Looper.prepare(). I will get Exception if I'm not using Looper.prepare(); – Akshay Kumar S Apr 19 '17 at 18:59
  • If you're getting an exception by not using prepare when you don't need to read a message queue, you're doing something else wrong. Probably making a Handler on the AsyncTask when you should be making it on the UI thread. – Gabe Sechan Apr 19 '17 at 19:00