Android中AsyncTask的使用

来源:互联网 发布:Ubuntu 软件怎么打不开 编辑:程序博客网 时间:2024/05/01 05:39


1.异步任务的实例必须在UI线程中创建。

2.execute(Params... params)方法必须在UI线程中调用。

3. 不能在doInBackground(Params... params)中更改UI组件的信息。

4 . 每个AsyncTask只能执行一次,多次调用会抛出错误。



AsyncTask<Params, Progress, Result>是一个抽象类,它定义了三个泛型参数。

1.Params:启动任务执行的输入参数类型。

2.Progress:任务进行时的参数类型。

3.Result:任务执行完后返回的结果类型。

1.onPreExecute():执行任务之前调用。

2.doInBackground(Params... params):真正执行任务的方法。在该方法中调用publishProgress(Progress... values)方法可以更新任务执行进度。

3.onProgressUpdate(Progress... values):更新任务执行进度。在doInBackground(Params... params)中调用publishProgress(Progress... values)方法将会触发该方法。

4.onPostExecute(Result result):doInBackground(Params... params)方法执行完毕后,系统自动调用该方法,并将返回值传递给该方法


onPreExecute()   onProgressUpdate(Progress... values)    onPostExecute(Result result)  

运行在UI线程中   可以更改UI 运行UI线程
doInBackground(Params... params):     可以运行非UI线程,实例:xml  :
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    xmlns:app="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"    android:layout_height="match_parent"    app:layout_behavior="@string/appbar_scrolling_view_behavior"    tools:showIn="@layout/activity_main" tools:context=".MainActivity">    <TextView        android:id="@+id/tv"        android:text="更新进度"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <Button        android:id="@+id/btn"        android:text="更新"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        /></LinearLayout>



  Button btn;    TextView tv;@Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);      btn = (Button) findViewById(R.id.btn);       tv = (TextView) findViewById(R.id.tv);        btn.setOnClickListener(new Button.OnClickListener() {            public void onClick(View v) {                update();            }        });        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        setSupportActionBar(toolbar);        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);        fab.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)                        .setAction("Action", null).show();            }        });    }

  // UI线程中初始化实例  执行excute    private void update(){        //1.异步任务的实例必须在UI线程中创建。       // 2.execute(Params... params)方法必须在UI线程中调用。        UpdateTextTask updateTextTask = new UpdateTextTask(this);        updateTextTask.execute();    }/** AsyncTask<Params, Progress, Result>是一个抽象类,它定义了三个泛型参数。1.Params:启动任务执行的输入参数类型。2.Progress:任务进行时的参数类型。3.Result:任务执行完后返回的结果类型。** */    class UpdateTextTask extends AsyncTask<Void,Integer,String> {        private Context context;        UpdateTextTask(Context context) {            this.context = context;        }        /**         * 运行在UI线程中,在调用doInBackground()之前执行         */        @Override        protected void onPreExecute() {            Toast.makeText(context,"开始更新",Toast.LENGTH_SHORT).show();            tv.setText("开始更新");        }        /**         * 后台运行的方法,可以运行非UI线程,可以执行耗时的方法         */        @Override        protected String doInBackground(Void... params) {            String result;            int progress=0;            while(progress<10){                progress++;                publishProgress(progress);   //其中的progress任务进行时的参数                                             // 标识任务运行进度 将其发布给onProgressUpdate                                             // onProgressUpdate 更新UI 显示任务进度              //  不在doInBackground(Params... params)中更改UI组件的信息。              // publishProgress(progress); 给onProgressUpdate                try {                    Thread.sleep(1000);                } catch (InterruptedException e) {                    result="更新出错!";                    return result;                }            }            result="更新完成!";                                     //其中的result任务运行结果                                      // 标识任务运行结果  将其返回给onPostExecute                                 // onPostExecute 更新UI 显示任务进度            return  result;        }        /**         * 运行在ui线程中,         * 在publishProgress()被调用以后执行,设置ui ,显示任务运行进度         * progress为任务运行进度         */        @Override        protected void onProgressUpdate(Integer... progress) {            tv.setText(""+progress[0]);            //progress为     publishProgress(progress); 显示任务运行进度        }        /**         * 运行在ui线程中,在doInBackground()执行完毕后执行 ,显示结果         * result 为doInBackground()的返回值         */        @Override        protected void onPostExecute(String result) {                          // result 为doInBackground()的返回值            Toast.makeText(context, result, Toast.LENGTH_SHORT).show();            tv.setText(result);        }






0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 苹果6app被锁了怎么办 捡的苹果id锁了怎么办 苹果手机id密码锁了怎么办 美版5s刷机后激活怎么办 vivo手机图案解锁忘记了怎么办 苹果5sid锁死了怎么办 苹果id账号被锁怎么办 苹果6s忘了ld怎么办 小米忘记图形解锁怎么办呢 索尼手机忘记解锁图案怎么办 oppoa37忘记锁屏密码怎么办 oppoa37锁屏密码忘了怎么办 oppor9图案密码忘了怎么办 oppor忘记锁屏图案怎么办 oppor手机忘记解锁图案怎么办 oppor手机忘记图案了怎么办 oppo手机屏幕锁忘了怎么办 三星手机屏幕锁忘了怎么办 手机主菜单坏了怎么办 索尼手机密码忘了怎么办 索尼笔记本密码忘了怎么办 索尼手机解锁密码忘了怎么办 索尼记录仪密码忘了怎么办 索尼z3手机忘记开机密码怎么办 索尼忘记锁屏密码怎么办 索尼手机忘记锁屏密码怎么办 忘了手机解锁图案怎么办 索尼手机忘记开机密码怎么办 索尼笔记本开机密码忘了怎么办 手机的开机密码忘了怎么办 联想手机开机密码忘了怎么办 红米note3忘记开机密码怎么办 小米2忘了密码怎么办 小米笔记本电脑忘记开机密码怎么办 小米笔记本忘记开机密码怎么办 小米手机儿童模式忘记密码怎么办 小米应用锁密码忘了怎么办 小米air密码忘了怎么办 小米4密码忘了怎么办 小米手机开机密码忘了怎么办? 小米笔记本电脑开机密码忘了怎么办