Android: got CalledFromWrongThreadException in onPostExecute() - How could it be?

后端 未结 6 730
你的背包
你的背包 2020-12-13 09:48

I have an app in production for a few weeks, using ACRA, and I had zero errors until one strange error reported today.

I\'ve got:

    android.view.Vi         


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 10:41

    Placing the following line of code in the Application onCreate should solve the problem:

         /**
         * Fixing AsyncTask Issue not called on main thread
         */
        try {
            Class.forName("android.os.AsyncTask");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    

    It seems the issue is created when the AsyncTask class is first initiated on a different main Thread which is not our main Thread, I checked it by adding the code in the bottom, to my Application onCreate

        new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
                Log.i("tag","1.3onPostExecute ran ON: " + Thread.currentThread().getId());
                Looper.prepare();
                new AsyncTask(){
                    @Override
                    protected Void doInBackground(Void... params) {
                        Log.i("tag","2onPostExecute ran ON: " + Thread.currentThread().getId());
                        return null;
                    }
    
                    @Override
                    protected void onPostExecute(Void aVoid) {
                        Log.i("tag","1.2onPostExecute ran ON: " + Thread.currentThread().getId());
                        super.onPostExecute(aVoid);
                    }
                }.execute();
                Looper.loop();
                Looper.myLooper().quit();
            }
        }).start();
    

    This code will init the AsynTask in a main Thread which is not the application main, and will cause the application to crash in any other AsyncTask which will do any UI on the post-execute. crashing with the CalledFromWrongThreadException

    Hope it cleared things a little bit more.

    Thanks all for the great help on this.

提交回复
热议问题