第一步创建AsyncTask实例
updateText=new UpdateText();
updateText.execute();
注意:创建实例放在点击按钮可以多次创建,放在ui线程点两次报错。
第二步继承AsyncTask并实现其中5个方法,按顺序执行!
@Override protected void onPreExecute() { super.onPreExecute(); Toast.makeText(AsyncTaskActivity.this, "开始倒计时", Toast.LENGTH_SHORT).show(); textView.setVisibility(View.VISIBLE); }
其中该方法用来初始化数据
@Override protected Integer doInBackground(Void... voids) { int i; for( i=5;i>0;i--){ if (this.isCancelled()) break; publishProgress(i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } return 0; }
其中该方法在子线程中运行,publishProgress(i)去更新UI进度,return 0结果提交给
onPostExecute和onCancelled
注意点:中断任务
updateText.cancel(true);但该任务还在执行
还需在doinbackground方法在循环体中提前跳出
if (this.isCancelled()) break;
后执行oncancelled方法