如何从AsyncTask修改MainActivity的TextView?

时间:2015-08-11 00:15:53

标签: android android-asynctask

我正在编写一个聊天应用程序,它有2个进程(获取和发送)。它们写在MainActivity中,工作方式如下:

options = {
            fileKey: 'file',
            fileName: name,
            chunkedMode: false,
            mimeType: 'audio/3gpp',
            httpMethod: 'PUT',
            // Important!
            headers: {
                'Content-Type': 'audio/3gpp' // < Set explicitly otherwise it becomes multipart/form-data which won't work with S3
            },
            encodeURI: false // < Stops any extra encoding by file transfer logic
        }

问题是来自Get的步骤(2.2)显然不起作用。

而不是它,我使用Log.d(&#34; Remote&#34;,MSG)在LogCat控制台上打印远程消息。

我的问题是:鉴于此TextView位于MainActivity(并且AsyncTask_GET是一个独立的类),如何从AsyncTask_GET修改此TextView?

2 个答案:

答案 0 :(得分:1)

如果它是独立的类,您可以向AsyncTask类添加构造函数并向其发送TextView,然后您可以在onPostExecute()方法中更改其文本,如:

public class GetMsg extends AsyncTask<Void, Void, Void> {
    private TextView msg;

    public GetMsg(TextView msg){
        this.msg = msg;
    }

    @Override
    protected void onPostExecute(Void result) {
        // Change the text of msg TextView
        msg.setText("Add your text here");
}

并且要调用它,只需在构造函数中添加TextView,如

TextView tv = (TextView) findViewById(R.id.textview); // your textview
new GetMsg(tv).execute();

答案 1 :(得分:0)

异步任务得到了buildin方法。它被称为onProgressUpdate,并且它在ui线程上运行。

private class DownloadFilesTask extends AsyncTask<URL, String, Long> {
     protected Long doInBackground(URL... urls) {

             publishProgress("hello from async task"); 
            // you call it just like this, but remember its array

         }
         return totalSize;
     }

     protected void onProgressUpdate(String... string) {

      textView.settext(string[0]); // and here you set the text

     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }