How to show toast in AsyncTask in doInBackground

后端 未结 9 767
灰色年华
灰色年华 2020-11-27 23:01

In one of my activities I\'m using AsyncTask. In doInBackground() I\'m making calls to various methods. In one of these methods I\'m getting an exc

9条回答
  •  生来不讨喜
    2020-11-27 23:26

    If you have to declare anything related to Thread, then it must be outside the runOnUiThread() method, then only it is going to execute,

        @Override
        protected String doInBackground(String... strings) {
            for(int i=0; i<10; i++) {
    
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Example for Toast "+i, Toast.LENGTH_SHORT).show();
                    }
                });
    
                try {
                    Thread.sleep(10);
                } catch (Exception e) {}
            }
    
            return "";
        }
    

提交回复
热议问题