Android异步任务AsyncTask使用

来源:互联网 发布:杭州网络推广公司排名 编辑:程序博客网 时间:2024/04/27 21:23

原文连接:http://www.cnblogs.com/soonfly/p/4669790.html

AsyncTask主要用来更新UI线程,比较耗时的操作可以在AsyncTask中使用。

AsyncTask是个抽象类,使用时需要继承这个类,然后调用execute()方法。注意继承时需要设定三个泛型Params,Progress和Result的类型,如AsyncTask<Void,Inetger,Void>:

  • Params是指调用execute()方法时传入的参数类型和doInBackgound()的参数类型
  • Progress是指更新进度时传递的参数类型,即publishProgress()和onProgressUpdate()的参数类型
  • Result是指doInBackground()的返回值类型
上面的说明涉及到几个方法:
  • doInBackgound() 这个方法是继承AsyncTask必须要实现的,运行于后台,耗时的操作可以在这里做
  • publishProgress() 更新进度,给onProgressUpdate()传递进度参数
  • onProgressUpdate() 在publishProgress()调用完被调用,更新进度

好了,看下实际的例子,了解一下怎么使用吧:

public class MyActivity extends Activity{    private Button btn;    private TextView tv;    @Override    public void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        btn = (Button) findViewById(R.id.start_btn);        tv = (TextView) findViewById(R.id.content);        btn.setOnClickListener(new Button.OnClickListener(){            public void onClick(View v) {                update();            }        });    }    private void update(){        UpdateTextTask updateTextTask = new UpdateTextTask(this);        updateTextTask.execute();    }    class UpdateTextTask extends AsyncTask<Void,Integer,Integer>{        private Context context;        UpdateTextTask(Context context) {            this.context = context;        }        /**         * 运行在UI线程中,在调用doInBackground()之前执行         */        @Override        protected void onPreExecute() {            Toast.makeText(context,"开始执行",Toast.LENGTH_SHORT).show();        }        /**         * 后台运行的方法,可以运行非UI线程,可以执行耗时的方法         */        @Override        protected Integer doInBackground(Void... params) {            int i=0;            while(i<10){                i++;                publishProgress(i);                try {                    Thread.sleep(1000);                } catch (InterruptedException e) {                }            }            return null;        }        /**         * 运行在ui线程中,在doInBackground()执行完毕后执行         */        @Override        protected void onPostExecute(Integer integer) {            Toast.makeText(context,"执行完毕",Toast.LENGTH_SHORT).show();        }        /**         * 在publishProgress()被调用以后执行,publishProgress()用于更新进度         */        @Override        protected void onProgressUpdate(Integer... values) {            tv.setText(""+values[0]);        }    }}

阅读全文
0 0
原创粉丝点击