我正在阅读有关AsyncTask的文章,并尝试了下面的简单程序。但这似乎并不奏效。我该怎么做呢?

public class AsyncTaskActivity extends Activity {

    Button btn;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener((OnClickListener) this);
    }

    public void onClick(View view){
        new LongOperation().execute("");
    }

    private class LongOperation extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            for(int i=0;i<5;i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed");
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }
}

我只是试图在后台进程中5秒后更改标签。

这是我的main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical" >
    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="10dip">
    </ProgressBar>
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Progress" >
    </Button>
    <TextView android:id="@+id/output"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Replace"/>
</LinearLayout>

当前回答

背景/理论

AsyncTask允许你在后台线程上运行一个任务,同时将结果发布到UI线程。

用户应该始终能够与应用程序进行交互,所以这很重要 以避免阻塞主(UI)线程的任务,如 从网上下载内容。 这就是我们使用AsyncTask的原因。 它通过包装UI线程消息队列和处理程序提供了一个简单的接口,允许您发送和处理来自其他线程的可运行对象和消息。

实现

AsyncTask是一个泛型类。(它在构造函数中接受参数化类型。)

它使用以下三种泛型类型:

Params -执行时发送给任务的参数类型。

进度-在后台计算期间发布的进度单元的类型。

结果——后台计算结果的类型。

异步任务并不总是使用所有类型。要将一个类型标记为未使用的,只需使用类型Void: 私有类MyTask扩展AsyncTask<Void, Void, Void>{…}

这三个参数对应三个你可以在AsyncTask中覆盖的主要函数:

doInBackground (Params…) onProgressUpdate(进步…) onPostExecute(结果)

执行AsyncTask

调用execute(),并将参数发送给后台任务。

会发生什么

On main/UI thread, onPreExecute() is called. To initialize something in this thread. (E.g. show a progress bar on the user interface.) On a background thread, doInBackground(Params...) is called. (Params were passed via execute.) Where the long-running task should happen. Must override at least doInBackground() to use AsyncTask. Call publishProgress(Progress...) to update the user interface with a display of progress (e.g. UI animation or log text printed) while the background computation is still executing. Causes onProgressUpdate() to be called. On the background thread a result is returned from doInBackground(). (This triggers the next step.) On main/UI thread, onPostExecute() is called with the returned result.

例子

在这两个例子中,“阻塞任务”都是从网上下载的。

示例A下载图像并在ImageView中显示它,而 例B下载一些文件。

一个例子

doInBackground()方法下载图像并将其存储在BitMap类型的对象中。onPostExecute()方法获取位图并将其放置在ImageView中。

class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bitImage;

    public DownloadImageTask(ImageView bitImage) {
        this.bitImage = bitImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mBmp = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mBmp = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mBmp;
    }

    protected void onPostExecute(Bitmap result) {
        bitImage.setImageBitmap(result);
    }
}

例B

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

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

例B执行

new DownloadFilesTask().execute(url1, url2, url3);

其他回答

我相信它是正确执行,但你试图改变UI元素在后台线程,这不会做。

修改你的调用和AsyncTask如下:

调用类

注意:我个人建议在任何执行AsyncTask线程的地方使用onPostExecute(),而不是在扩展AsyncTask本身的类中。我认为这使代码更容易阅读,特别是如果你需要AsyncTask在多个地方处理略有不同的结果。

new LongThread() {
    @Override public void onPostExecute(String result) {
        TextView txt = (TextView) findViewById(R.id.output);
        txt.setText(result);
    }
}.execute("");

LongThread类(extends AsyncTask):

@Override
protected String doInBackground(String... params) {
    for (int i = 0; i < 5; i++) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    return "Executed";
}      

当你在工作线程中,你不能直接操作Android上的UI元素。

当你使用AsyncTask时,请理解回调方法。

例如:

public class MyAyncTask extends AsyncTask<Void, Void, Void>{

    @Override
    protected void onPreExecute() {
        // Here you can show progress bar or something on the similar lines.
        // Since you are in a UI thread here.
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        // After completing execution of given task, control will return here.
        // Hence if you want to populate UI elements with fetched data, do it here.
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
        // You can track you progress update here
    }

    @Override
    protected Void doInBackground(Void... params) {
        // Here you are in the worker thread and you are not allowed to access UI thread from here.
        // Here you can perform network operations or any heavy operations you want.
        return null;
    }
}

仅供参考: 要从工作线程访问UI线程,您可以在视图上使用runOnUiThread()方法或post方法。

例如:

runOnUiThread(new Runnable() {
    textView.setText("something.");
});

or
    yourview.post(new Runnable() {
    yourview.setText("something");
});

这将帮助你更好地了解事情。因此在你的情况下,你需要在onPostExecute()方法中设置你的textview。

我的完整答案在这里,但这里有一个解释性的图像来补充本页上的其他答案。对我来说,理解所有变量的走向是最让我困惑的部分。

好的,您正在尝试通过另一个线程访问GUI。总的来说,这不是一种好的做法。

AsyncTask在另一个线程中执行doInBackground()中的所有内容,该线程不能访问视图所在的GUI。

preExecute()和postExecute()提供了在这个新线程中发生重大操作之前和之后访问GUI的权限,甚至可以将长时间操作的结果传递给postExecute(),然后显示处理的任何结果。

看到这些行,你稍后更新你的TextView:

TextView txt = findViewById(R.id.output);
txt.setText("Executed");

把它们放在onPostExecute()中。

然后你会看到你的TextView文本更新后,doInBackground完成。

我注意到你的onClick监听器没有检查哪个视图已被选中。我发现最简单的方法是通过switch语句。我有一个完整的类编辑下面所有的建议,以避免混乱。

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class AsyncTaskActivity extends Activity implements OnClickListener {

    Button btn;
    AsyncTask<?, ?, ?> runningTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = findViewById(R.id.button1);

        // Because we implement OnClickListener, we only
        // have to pass "this" (much easier)
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        // Detect the view that was "clicked"
        switch (view.getId()) {
        case R.id.button1:
            if (runningTask != null)
                runningTask.cancel(true);
            runningTask = new LongOperation();
            runningTask.execute();
            break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Cancel running task(s) to avoid memory leaks
        if (runningTask != null)
            runningTask.cancel(true);
    }

    private final class LongOperation extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // We were cancelled; stop sleeping!
                }
            }
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed"); // txt.setText(result);
            // You might want to change "executed" for the returned string
            // passed into onPostExecute(), but that is up to you
        }
    }
}
private class AsyncTaskDemo extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {

        // Do code here

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    protected void onCancelled() {

        super.onCancelled();
        progressDialog.dismiss();
        Toast toast = Toast.makeText(
                          getActivity(),
                          "An error is occurred due to some problem",
                          Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP, 25, 400);
        toast.show();
    }

}