android AsyncTask实例

时间:2023-03-09 01:55:28
android AsyncTask实例

android AsyncTask实例

.java

 package com.example.activitydemoay;

 import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView; public class MainActivity extends Activity { Button download;
ProgressBar pb;
TextView tv; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); pb = (ProgressBar) findViewById(R.id.pb);
tv = (TextView) findViewById(R.id.tv); download = (Button) findViewById(R.id.download);
download.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DownloadTask dTask = new DownloadTask();
dTask.execute(100);
}
});
} class DownloadTask extends AsyncTask<Integer, Integer, String> {
// 后面尖括号内分别是参数(例子里是线程休息时间),进度(publishProgress用到),返回值 类型 @Override
protected void onPreExecute() {
// 第一个执行方法
super.onPreExecute();
} @Override
protected String doInBackground(Integer... params) {
// 第二个执行方法,onPreExecute()执行完后执行
for (int i = 0; i <= 100; i++) {
pb.setProgress(i);
publishProgress(i);
try {
Thread.sleep(params[0]);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "执行完毕";
} @Override
protected void onProgressUpdate(Integer... progress) {
// 这个函数在doInBackground调用publishProgress时触发,虽然调用时只有一个参数
// 但是这里取到的是一个数组,所以要用progesss[0]来取值
// 第n个参数就用progress[n]来取值
tv.setText(progress[0] + "%");
super.onProgressUpdate(progress);
} @Override
protected void onPostExecute(String result) {
// doInBackground返回时触发,换句话说,就是doInBackground执行完后触发
// 这里的result就是上面doInBackground执行后的返回值,所以这里是"执行完毕"
setTitle(result);
Intent intent = new Intent();
// Intent传递参数
// intent.putExtra("TEST", "123");
// intent.setClass(MainActivity.this, MainActivityB.class);
// MainActivity.this.startActivity(intent);
super.onPostExecute(result);
} } }

.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello , Welcome to Andy's Blog!"/>
<Button
android:id="@+id/download"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Download"/>
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="当前进度显示"/>
<ProgressBar
android:id="@+id/pb"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"/>
</LinearLayout>