AsyncTask
定义
AsyncTask是Android提供的轻量级的异步类;
AsyncTask直接继承object类,位于android.os包中;
AysncTask可以帮助我们创建后台线程,开发者只需简单的重写几个回调函数,就可以完成后台子线程处理耗时操作,再将结果更新到UI线程的操作。
用法
AsyncTask的三种泛型参数:
Params:启动任务执行的输入参数;
Progress:后台任务执行的百分比;
Result:后台执行任务最终返回的结果。
使用AsyncTask,可以重写四个回调函数
//在UI线程调用,在doInBackground之前执行
protected void onPreExecute()
//在后台线程调用,完成后台任务的方法主体,抽象方法,AsyncTask的子类必须重写该方法
protected abstract Result doInBackground(Params... params)
//在UI线程调用,显示操作进度
protected void onProgressUpdate(Progress... values)
//在UI线程调用,在doInBackground之后执行
protected void onPostExecute(Result result)
使用AsyncTask做倒计时
代码展示
xml文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.asyncapplication.DaojishiActivity">
<EditText
android:id="@+id/daojishi_et"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/daojishi_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="倒计时"
android:textSize="30sp"/>
<Button
android:id="@+id/daojishi_btn"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="开始倒计时"
android:textSize="20sp"/>
</LinearLayout>
Java文件
package com.example.administrator.asyncapplication;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DaojishiActivity extends AppCompatActivity {
private EditText daojishiET;
private TextView daojishiTV;
private Button daojishiBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daojishi);
bindID();
daojishiBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int time=Integer.parseInt(daojishiET.getText().toString());//Integer就是代表整型对象,parseInt就是一个转换方法。将String字符类型数据转换为Integer整型数据
new MyTask().execute(time);
}
});
}
private void bindID() {
daojishiET=findViewById(R.id.daojishi_et);
daojishiBtn = findViewById(R.id.daojishi_btn);
daojishiTV = findViewById(R.id.daojishi_tv);
}
class MyTask extends AsyncTask<Integer,Integer,String>{
@Override
protected String doInBackground(Integer... integers) {
for (int i=integers[0];i>0;i--){
try {
Thread.sleep(1000);
publishProgress(i);//调用onProgressUpdate方法
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "计时结束";
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
daojishiTV.setText(values[0]+"");
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
daojishiTV.setText(s);
}
}
}
使用AsyncTask做进度条
代码展示
xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.asyncapplication.ProgressActivity">
<SeekBar
android:id="@+id/main_bar1"
android:layout_width="match_parent"
android:layout_height="40dp" />
<SeekBar
android:id="@+id/main_bar2"
android:layout_width="match_parent"
android:layout_height="40dp" />
<Button
android:id="@+id/main_btn1"
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="1开始下载"/>
<Button
android:id="@+id/main_btn2"
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="2开始下载"/>
</LinearLayout>
Java文件
package com.example.administrator.asyncapplication;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
public class ProgressActivity extends AppCompatActivity implements View.OnClickListener{
private SeekBar seekBar1;
private SeekBar seekBar2;
private Button button1;
private Button button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
bindID();
}
private void bindID() {
seekBar1 = findViewById(R.id.main_bar1);
seekBar2 = findViewById(R.id.main_bar2);
button1 = findViewById(R.id.main_btn1);
button2 = findViewById(R.id.main_btn2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
seekBar1.setMax(10);
seekBar2.setMax(10);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.main_btn1:
button1.setEnabled(false);
button1.setText("正在下载");
new MyTask().execute(1);
break;
case R.id.main_btn2:
button2.setEnabled(false);
button2.setText("正在下载");
new MyTask().execute(2);
break;
}
}
class MyTask extends AsyncTask<Integer, Integer, Integer> {
@Override
protected Integer doInBackground(Integer... integers) {
int whichPb = integers[0];
for (int i = 0; i <= 10; i++) {
try {
Thread.sleep(1000);
publishProgress(i,whichPb);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return whichPb;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
switch (values[1]) {
case 1:
seekBar1.setProgress(values[0]);
break;
case 2:
seekBar2.setProgress(values[0]);
break;
}
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
switch (integer) {
case 1:
button1.setText("下载完成");
button1.setEnabled(true);
break;
case 2:
button2.setText("下载完成");
button2.setEnabled(true);
break;
}
}
}
}
Execute与 ExecuteonExecutor区别
执行execute()方法线程只能串行
执行executeOnExecuter()方法线程并行运行,同时只能启动五个线程
AsyncTask Handler
AsyncTask,是android提供的轻量级的异步类,可以直接继承AsyncTask,可以通过接口实现UI进度更新,最后反馈执行的结果给UI主线程.
使用:简单,快捷,过程可控
Handler 异步实现时,涉及到 Handler, Looper, Message,Thread四个对象,实现异步的流程是主线程启动Thread(子线程)àthread(子线程)运行并生成Message-àLooper获取Message并传递给HandleràHandler逐个获取Looper中的Message,并进行UI变更。
使用:在单个后台异步处理时,显得代码过多,结构过于复杂(相对性)