代码
public class MainActivity extends Activity {
TextView show;
ImageView iv ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (TextView)findViewById(R.id.show);
iv= (ImageView)findViewById(R.id.iv);
}
public void download(View v) throws MalformedURLException{
DownTask task = new DownTask(this);
task.execute(new URL("http://www.baidu.com"));
}
public void downloadPic(View v) throws MalformedURLException{
DownPic task = new DownPic(this);
task.execute(new URL("http://h.hiphotos.baidu.com/image/w%3D2048/sign=24753a258501a18bf0eb154faa170608/42166d224f4a20a4e98280ce92529822720ed01f.jpg"));
}
private class DownPic extends AsyncTask<URL, Integer, Bitmap>{
Context context;
public DownPic(Context c) {
context = c;
}
@Override
protected Bitmap doInBackground(URL... params) {
try {
Bitmap pic = BitmapFactory.decodeStream(params[0].openStream());
return pic;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
iv.setImageBitmap(result);
}
}
private class DownTask extends AsyncTask<URL, Integer, String>{
ProgressDialog pdialog;
int hasRead = 0;
Context mContext;
public DownTask(Context context) {
mContext=context;
}
@Override
protected String doInBackground(URL... params) {
StringBuilder sb = new StringBuilder();
try {
URLConnection conn = params[0].openConnection();
//打开conn连接对应的输入流,并将它包装成BufferredReader
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line = null;
while((line = br.readLine())!=null){
sb.append(line);
hasRead++;
publishProgress(hasRead);
}
return sb.toString();
} catch (Exception e) {
}
return null;
}
@Override
protected void onPostExecute(String result) {
//返回HTML页面内容
show.setText(result);
pdialog.dismiss();
}
@Override
protected void onPreExecute() {
pdialog = new ProgressDialog(mContext);
pdialog.setTitle("任务正在执行...");
pdialog.setMessage("任务正在执行中,请等待...");
pdialog.setCancelable(false);
pdialog.setMax(202);
pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pdialog.setIndeterminate(false);//是否显示进度条
pdialog.show();
}
@Override
protected void onProgressUpdate(Integer... values) {
//更新进度条
show.setText("已经读取了["+values[0]+"]行");
pdialog.setProgress(values[0]);
}
}
}
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="download"
android:text="down Text" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="downloadPic"
android:text="down img" />
</LinearLayout>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/show"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minLines="4"
android:text="@string/hello_world" />
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
</LinearLayout>
</ScrollView>
</LinearLayout>
AsyncTask抽象类、 定义了三种泛型类型 Params,Progress和Result。
Params 启动任务执行的输入参数,比如HTTP请求的URL。
Progress 后台任务执行的百分比。
Result 后台执行任务最终返回的结果。
Params 启动任务执行的输入参数,比如HTTP请求的URL。
Progress 后台任务执行的百分比。
Result 后台执行任务最终返回的结果。
AsyncTask的执行分为四个步骤,每一步都对应一个回调方法,我们需要做的就是实现这些方法。
1) 继承AsyncTask
2) 重写AsyncTask中定义的一个或多个方法
onPreExecute(), 该方法将在执行实际的后台操作前被UI thread调用。可以在该方法中做一些准备工作,如在界面上显示一个
1) 继承AsyncTask
2) 重写AsyncTask中定义的一个或多个方法
onPreExecute(), 该方法将在执行实际的后台操作前被UI thread调用。可以在该方法中做一些准备工作,如在界面上显示一个
进度条。
doInBackground(Params...), 将在onPreExecute 方法执行后马上执行,该方法运行在后台线程中。这里将主要负责执行那些
doInBackground(Params...), 将在onPreExecute 方法执行后马上执行,该方法运行在后台线程中。这里将主要负责执行那些
很耗时的后台计算工作。可以调用 publishProgress方法来更新实时的任务进度。该方法是抽象方法,子类必须实现。
onProgressUpdate(Progress...),在publishProgress方法被调用后,UI thread将调用这个方法从而在界面上展示任务的进展
onProgressUpdate(Progress...),在publishProgress方法被调用后,UI thread将调用这个方法从而在界面上展示任务的进展
情况,例如通过一个进度条进行展示。
onPostExecute(Result), 在doInBackground 执行完成后,onPostExecute 方法将被UI thread调用,后台的计算结果将通过该方法传递到UI thread.
onPostExecute(Result), 在doInBackground 执行完成后,onPostExecute 方法将被UI thread调用,后台的计算结果将通过该方法传递到UI thread.
为了正确的使用AsyncTask类,以下是几条必须遵守的准则:
1) Task的实例必须在UI thread中创建
2) execute方法必须在UI thread中调用
3) 不要手动的调用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate
1) Task的实例必须在UI thread中创建
2) execute方法必须在UI thread中调用
3) 不要手动的调用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate
(Progress...)这几个方法
4) 该task只能被执行一次,否则多次调用时将会出现异常
4) 该task只能被执行一次,否则多次调用时将会出现异常