主要是异步任务类的一个小例子。
AsyncTask 类用于异步执行任务。使用它必须继承AsyncTask,而且指定3个泛型值:
Params:传给执行任务的参数值类型
Progress: 任务在后台执行的进度条类型,通常为Integer。
Result: 执行完任务的返回值类型
AsyncTask的子类必须要实现doInBackground的方法,通常在改方法执行后台任务,除此之外还有
onPoseExecute方法 :任务执行完后被调用
onProgressUpdata 方法 : 任务处理的过程中调用, 也传递当前进度值, 主要是调用AsyncTask.publishProcess方法后会调用
onCanceled:(当任务取消时被调用)
其中onPostExecute,onProgressUpdate和onCancel方法中都可以访问UI线程的控件,doInBackground只能访问非Ui线程控件的代码
因为涉及到网络 记得要添加网络权限
<uses-permission android:name="android.permission.INTERNET" />
public class MainActivity extends Activity implements OnClickListener {
private Button startBtn;
private Button stopBtn;
private MyAsyncTask myAsyncTask;
private String imgPath = "http://c.hiphotos.baidu.com/image/pic/item/37d12f2eb9389b50bdca45c68735e5dde7116e69.jpg";
private Bitmap bm;
private ProgressDialog mProgressDialog;
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
mImageView = (ImageView) findViewById(R.id.imageView1);
startBtn = (Button) findViewById(R.id.button1);
stopBtn = (Button) findViewById(R.id.button2);
startBtn.setOnClickListener(this);
stopBtn.setOnClickListener(this);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle("提示信息");
mProgressDialog.setMessage("正在下载中...");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
class MyAsyncTask extends AsyncTask<String, Integer, Void> {
@Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
ByteArrayOutputStream bos= new ByteArrayOutputStream();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
InputStream is = null;
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
is = httpResponse.getEntity().getContent();
long sum = httpResponse.getEntity().getContentLength();
byte[] buffer = new byte[1024];
int count = 0;
int process = 0;
while ((count = is.read(buffer)) != -1) {
bos.write(buffer, 0, count);
process = process + count;
publishProgress((int) (process / (float) sum * 100));
}
byte[] data = bos.toByteArray();
bm = BitmapFactory.decodeByteArray(data, 0, data.length);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(bos != null){
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mImageView.setImageBitmap(bm);
mProgressDialog.cancel();
Toast.makeText(MainActivity.this, "download successfully",
Toast.LENGTH_SHORT).show();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Log.i("jiayou", "values" + values[0]);
mProgressDialog.setProgress(values[0]);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
onClick_start();
break;
case R.id.button2:
onClick_stop();
break;
default:
break;
}
}
private void onClick_stop() {
myAsyncTask.cancel(true);
mProgressDialog.cancel();
}
private void onClick_start() {
myAsyncTask = new MyAsyncTask();
myAsyncTask.execute(imgPath);
mProgressDialog.show();
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="57dp"
android:text="start" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:text="stop" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@+id/button2"
android:scaleType="fitCenter"
android:layout_marginTop="66dp" />
</RelativeLayout>