1.AsyncTask是什么
1.AsyncTask是Android提供的轻量级的异步类
2.为了降低开发者的难度,提供了AsyncTask
2.下面我我们用一个倒计时的例子来实现AsyncTask
1.布局文件
<?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.mysky.Download">
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:textSize="50sp"
android:id="@+id/dl_tv"/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="开始下载"
android:id="@+id/dl_btn"/>
</LinearLayout>
2.创建一个内部类继承自AsyncTask 实现 doInBackground方法
class DownloadTask extends AsyncTask<String,String,String>
@Override
protected String doInBackground(String... strings) {
3.使用onPostExecute方法来显示结果
protected void onPostExecute(String s) {
super.onPostExecute(s);
dlTV.setText(s);
4.return返回的值由给了 onPostExecute中的String并用 dlTV.setText赋值给s
protected void onPostExecute(String s) {
super.onPostExecute(s);
dlTV.setText(s);
5.调用onProgressUpdate刷新线程 但是这个方法喜欢被动 我们得用一个方法去触发它 也就是勾引它
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
使用publishProgress去触发它
protected String doInBackground(String... strings) {
while (count>0){
publishProgress(count+"");
count--;
6.完整Java代码如下
package com.example.administrator.mysky;
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.TextView;
public class Download extends AppCompatActivity {
private TextView dlTV;
private Button dlBtn;
private int count=10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
dlTV=findViewById(R.id.dl_tv);
dlBtn=findViewById(R.id.dl_btn);
dlBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new DownloadTask().execute();
}
});
}
class DownloadTask extends AsyncTask<String,String,String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
dlTV.setText("正在下载");
}
@Override
protected String doInBackground(String... strings) {
while (count>0){
publishProgress(count+"");
count--;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "下载完成";
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
dlTV.setText(values[0]);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
dlTV.setText(s);
}
}
}
3..什么是长度可变的参数列表
长度可变的参数列表就是上述onProgressUpdate方法中String后边的三个点,传参数的时候不限制参数数量
protected void onProgressUpdate(String... values)