异步任务类 AsyncTask 中的几个方法(其中doInBackground()是 必须要实现的):
public class MyAnsy extends AsyncTask<Void,Void,Integer>{
//参数1 Params是指调用execute()方法时传入的参数类型和doInBackgound()的参数类型
//参数2 Progress是指更新进度时传递的参数类型,即publishProgress()和onProgressUpdate()的参数类型
//参数3 Result是指doInBackground()的返回值类型
@Override
//主线程
protected void onPreExecute() { //执行之前
super.onPreExecute();
}
@Override
//子线程
protected Integer doInBackground(Void... params) { //后台耗时的操作
//子线程
publishProgress();//更新进度,给onProgressUpdate()传递进度参数
return 0;
}
@Override
//主线程
protected void onPostExecute(Integer integer) { //在doInBackground()执行完毕后执行
super.onPostExecute(integer);
}
@Override
//主线程
protected void onProgressUpdate(Void... values) { // 在publishProgress()调用完被调用,更新进度
super.onProgressUpdate(values);
}
}
通过异步任务类来设置TextView
public class MyTextAnsy extends AsyncTask<Void,Integer,Integer>{
@Override
protected Integer doInBackground(Void... params) {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i);
}
return 1;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
tvshow.setText(String.valueOf(values[0]));
}
}
通过异步任务类来设置ProgressDialog
public class MyProgress extends AsyncTask<Void,Integer,Integer>{
@Override
protected void onPreExecute() {
super.onPreExecute();
pd.setTitle("下载");
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("数据下载中......");
pd.setMax(100);
pd.show();
}
@Override
protected Integer doInBackground(Void... params) {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i);
}
return 1;
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if(result==1){
pd.dismiss();
}
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pd.setProgress(values[0]);
pd.setSecondaryProgress(values[0]*2);
}
}