android开发笔记之AsyncTask

这里写图片描述

引言

android开发时,我们经常遇到处理后台的耗时的操作,并且要实时的把后台操作的情况显示在UI界面。
一般,我们会采用handler+Thread的方式来处理,但是此种方式逻辑比较复杂,自己要写许多代码,其实android提供了一个AsyncTask类,可以非常方便的处理此种需求。

AsyncTask官方说明

AsyncTask

android.os.AsyncTask<Params, Progress, Result>

AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask 方便我们执行一些后台操作,并实时的把后台结果更新到UI线程,在这过程中不需要我们使用threads 和 handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

AsyncTask是一个帮助类,它非常适合一个后台短耗时操作(最多几秒)。如果你要使后台进程保持运行非常长的时间,强烈推荐你使用 Executor, ThreadPoolExecutor 和FutureTask

一个Demo

此Demo主要的作用是在后台开一个耗时操作,500ms更新一下进度条。非常简单,但是非常实用。

这里写图片描述

布局文件:

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <Button
            android:id="@+id/execute"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:onClick="onClickExecute"
            android:background="@drawable/button_click"
            android:text="execute"/>
        <Button
            android:id="@+id/cancel"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:onClick="onClickCancel"
            android:background="@drawable/button_click"
            android:enabled="false"
            android:text="cancel"/>
        <ProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:progress="0"
            android:max="100"
            style="?android:attr/progressBarStyleHorizontal"/>
        <TextView
            android:id="@+id/text_view"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout >

java实现:

public class TestActivity extends AppCompatActivity {

    public static final String TAG = "AsyncTask";

    private Button execute;
    private Button cancel;
    private ProgressBar progressBar;
    private TextView textView;
    private MyTask mTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        init();
    }

    private void init() {
        execute = (Button) findViewById(R.id.execute);
        cancel = (Button) findViewById(R.id.cancel);
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        textView = (TextView) findViewById(R.id.text_view);

    }

    public void onClickExecute(View view){
        Log.i(TAG, "onClickExecute:");
        //开始执行异步操作,输入二个参数,这二个参数在doInBackground方法中可以读取
        mTask = new MyTask();
        mTask.execute("params[0]--start run background logic","params[1]--0");

        execute.setEnabled(false);
        cancel.setEnabled(true);
    }

    public void onClickCancel(View view){
        Log.i(TAG, "onClickCancel:");
        mTask.cancel(true);
    }
    //成员变量AsyncTask
    private class MyTask extends AsyncTask<String, Integer, String> {

        //最先执行的方法,主要是做一些初始化工作
        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute() called");
            textView.setText("loading...");
        }

        //后台执行的耗时操作
        @Override
        protected String doInBackground(String... params) {
            Log.i(TAG, "doInBackground(Params... params) called");
            //在这可以获取参数
            Log.i(TAG, "doInBackground--params[0]:"+params[0]);
            Log.i(TAG, "doInBackground--params[1]:"+params[1]);

            int progress = 0;

            while (progress <= 100){
                try {
                    Thread.sleep(500);
                    progress = progress + 1;
                    Log.i(TAG, "doInBackground--progress:"+progress);
                    //使用此方法触发onProgressUpdate方法
                    publishProgress(progress);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if(progress == 101){
                //这是返回result参数,也就是onPostExecute方法中的String result
                return "result_success!";
            }else {
                //这是返回result参数,也就是onPostExecute方法中的String result
                return "result_fail!";
            }

        }

        //更新进展条
        @Override
        protected void onProgressUpdate(Integer... progresses) {
            Log.i(TAG, "onProgressUpdate(Progress... progresses) called");
            progressBar.setProgress(progresses[0]);
            textView.setText("loading..." + progresses[0] + "%");
        }
        //最后执行的一个方法
        @Override
        protected void onPostExecute(String result) {
            Log.i(TAG, "onPostExecute(Result result) called");
            Log.i(TAG, "onPostExecute---result:"+result);
            textView.setText(result);
            execute.setEnabled(true);
            cancel.setEnabled(false);
        }
        //取消时执行的方法
        @Override
        protected void onCancelled() {
            Log.i(TAG, "onCancelled() called");
            textView.setText("cancelled");
            progressBar.setProgress(0);
            execute.setEnabled(true);
            cancel.setEnabled(false);
        }
    }
}

参考资料

1.详解Android中AsyncTask的使用
http://blog.csdn.net/liuhe688/article/details/6532519
2.AsyncTask
https://developer.android.com/reference/android/os/AsyncTask.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hfreeman2008

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值