AsyncTaskActivity
package org.wp.activity;
import java.io.InputStream;
import java.text.DecimalFormat;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.Config;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AsyncTaskActivity extends Activity {
/** Context对象 **/
private Context mContext;
/** 开始加载图片 **/
private Button myButton;
/** 显示加载进度 **/
private TextView myTextView;
/** 加载图片开始时间 **/
private Long mLoadStartTime = 0L;
/** 加载图片结束时间 **/
private Long mLoadEndTime = 0L;
/** 格式化对象 **/
private DecimalFormat decf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.asynctask);
mContext = this;
decf = new DecimalFormat("0.00");
myTextView = (TextView) this.findViewById(R.id.myTextView);
myButton = (Button) this.findViewById(R.id.myButton);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadImage();
}
});
}
private void loadImage() {
/**
* AsyncTask 定义了三种泛型类型 Params,Progress和Result。
* Params 启动任务执行的输入参数,比如HTTP请求的URL。
* Progress 后台任务执行的百分比。
* Result 后台执行任务最终返回的结果,比如String。
*/
new AsyncTask<Void, Double, Long>() {
@Override
protected void onPreExecute() {
myTextView.setText("开始加载图片");
}
@Override
protected Long doInBackground(Void... params) {
mLoadStartTime = System.currentTimeMillis();
for (int i = 0; i < 2000; i++) {
readBitmap(mContext, R.drawable.one_piece);
double percent = (double) (i + 1) * 100 / 2000;
publishProgress(percent); // 更新百分比
}
mLoadEndTime = System.currentTimeMillis();
return mLoadEndTime - mLoadStartTime;
}
@Override
protected void onProgressUpdate(Double... values) {
myTextView.setText("当前加载进度" + decf.format(values[0]) + "%");
}
@Override
protected void onPostExecute(Long result) {
myTextView.setText("读取2000张图片一共耗时" + result + "毫秒");
}
}.execute();
}
/**
* 读取图片
*
* @param context
* @param resId
* @return Bitmap
*/
public Bitmap readBitmap(Context context, int resId) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Config.RGB_565;
opts.inPurgeable = true;
opts.inInputShareable = true;
InputStream is = context.getResources().openRawResource(resId);
return BitmapFactory.decodeStream(is, null, opts);
}
}
asynctask.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="AsyncTask循环加载2000张图片" android:id="@+id/myButton" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:text="点击按钮开始加载图片" android:id="@+id/myTextView" /> </LinearLayout>