案例一:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.administrator.asynctask.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="asyncTask"
android:onClick="asyncTaskClick"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:id="@+id/info"
android:layout_below="@+id/button"
android:layout_centerHorizontal="true" />
</RelativeLayout>
MainActivity.java
package com.example.administrator.asynctask;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private TextView info;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView) findViewById(R.id.info);
}
public void asyncTaskClick(View view) {
new MyAsyncTask(this).execute();
}
/*通过一个AsyncTask实现一个异步任务*/
private static class MyAsyncTask extends AsyncTask<String, Integer, String> {
private MainActivity activity;
public MyAsyncTask(MainActivity activity) {
this.activity = activity;
}
//执行任务之前触发的事件方法,可以在该方法中做一些初始化动作
@Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("onPreExecute");
activity.info.setText("开始执行任务。。。。");
}
// 执行后台任务的方法 ,类似于线程,所以不能在该方法中访问UI组件
//负责执行耗时操作
@Override
protected String doInBackground(String... params) {
for (int i = 0; i < 10; i++) {
System.out.println(i);
publishProgress(i);//更新进度
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "success";
}
//用来更新进度值
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
activity.info.setText("当前的值为:" + values[0]);
}
//当doInBackground方法返回后被调用
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
activity.info.setText(s);
}
}
}
案例二.下载文件示例
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.administrator.asynctask.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="asyncTask"
android:onClick="asyncTaskClick"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:id="@+id/info"
android:layout_below="@+id/button"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载"
android:onClick="downloadClick"
android:id="@+id/button2"
android:layout_below="@+id/info"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/info"
android:layout_alignEnd="@+id/info" />
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
android:layout_below="@+id/button2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
MainActivity.java
package com.example.administrator.asynctask;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends ActionBarActivity {
private TextView info;
private ProgressBar pb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView) findViewById(R.id.info);
pb = (ProgressBar) findViewById(R.id.progressBar);
}
public void asyncTaskClick(View view) {
new MyAsyncTask(this).execute();
}
/*通过一个AsyncTask实现一个异步任务*/
private static class MyAsyncTask extends AsyncTask<String, Integer, String> {
private MainActivity activity;
public MyAsyncTask(MainActivity activity) {
this.activity = activity;
}
//执行任务之前触发的事件方法,可以在该方法中做一些初始化动作
@Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("onPreExecute");
activity.info.setText("开始执行任务。。。。");
}
// 执行后台任务的方法 ,类似于线程,所以不能在该方法中访问UI组件
//负责执行耗时操作
@Override
protected String doInBackground(String... params) {
for (int i = 0; i < 10; i++) {
System.out.println(i);
publishProgress(i);//更新进度
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "success";
}
//用来更新进度值
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
activity.info.setText("当前的值为:" + values[0]);
}
//当doInBackground方法返回后被调用
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
activity.info.setText(s);
}
}
public void downloadClick(View view) {
new DownloadAsyncTask(this).execute("http://p1.gexing.com/shaitu/20120922/2210/505dc6e5c0e52.jpg");
}
private static class DownloadAsyncTask extends AsyncTask<String, Integer, Integer> {
private MainActivity activity;
public DownloadAsyncTask(MainActivity activity) {
this.activity = activity;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("onPreExecute");
activity.pb.setProgress(0);
}
@Override
protected Integer doInBackground(String... params) {
String s = params[0];
try {
URL url = new URL(s);
//打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int size = conn.getContentLength();//获取文件的大小
//0标记 表示需要更新最大进度值,1表示,更新当前下载的进度值
publishProgress(0, size);
byte[] bytes=new byte[20];
int len=-1;
InputStream in=conn.getInputStream();
FileOutputStream out=new FileOutputStream("/sdcard/"+System.currentTimeMillis()+".jpg");
while ((len=in.read(bytes))!=-1)
{
out.write(bytes,0,len);
publishProgress(1, len);//更新进度
out.flush();
// Thread.sleep(500);
}
out.close();
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 200;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
switch (values[0]) {
case 0:
activity.pb.setMax(values[1]);
break;
case 1:
activity.pb.incrementProgressBy(values[1]);
break;
}
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if (integer==200)
{
activity.info.setText("下载完成");
}
}
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>