在Looper.loop()之后不执行onPostExecute()

时间:2017-04-19 18:46:19

标签: android android-asynctask android-looper

doInBackground()工作正常..Looper.loop()之后的代码无效。在Looper.Loop()之后不记录并且不执行onPostExceute()。我需要等到方法1,2,3执行。如果未使用Looper.prepare(),则在method1中会发生异常。

@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() {
        //.....
    }

1 个答案:

答案 0 :(得分:2)

Looper.loop使线程循环永远等待消息队列上的传入事件并运行相关的runnables。永远不应该在AsyncTask上调用它,它将导致整个AsyncTask线程无限循环,使所有未来的AsyncTask死锁。它应该仅在线程上调用,并且只有在您了解如何使用它时才会被调用。

相关问题