AsyncTask无法在线程android中工作

R4j*_*R4j 1 android thread-safety android-asynctask

我使用AsyncTask来更改TextView的文本,如下所示:

    private class LongOperation extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        String response = "";
        for (String url : urls) {
            response += url;
        }
        return response;
    }

    @Override
    protected void onPostExecute(String result) {
        textView.setText(result);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我在OnClick事件中调用它,一切都会好的:

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    textView = (TextView) findViewById(R.id.txt);
    Button button = (Button)this.findViewById(R.id.button);
    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
          new LongOperation().execute(new String[]{"Hello"});
        }
      });
   }
Run Code Online (Sandbox Code Playgroud)

但是当我在我的线程中调用它时,该程序被迫关闭

this.closeButton.setOnClickListener(new OnClickListener() {
         @Override
        public void onClick(View v) {
          Thread t= new Thread(){               
           @Override
             public void run(){                                     
              try{
                    //Do something
                    //Then call AsyncTask
                new LongOperation().execute(new String[]{"Hello"});

               }catch(Exception e){}
         }
        };      
         t.start();
        }
      });
Run Code Online (Sandbox Code Playgroud)

我哪里错了?我不明白差异如何在线程中调用AsyncTask.

Phi*_*llo 8

我建议您查阅AsyncTask文档和进程和线程,以便更好地了解它的工作原理.实质上,您应该在主线程上创建AsyncTask子类.

当您调用AsyncTask.execute()时,在主线程上调用您提供的AsyncTask.onPreExecute,因此您可以进行UI设置.

接下来调用AsyncTask.doInBackground方法,并在其自己的线程中运行.

最后,当您的AsyncTask.doInBackground方法完成时,在主线程上调用AsyncTask.onPostExecute,您可以进行任何UI清理.

如果需要从AsyncTask.doInBackground方法中更新UI ,请调用AsyncTask.publishProgress,它将在主线程中调用onProgressUpdate.