AsyncTask异步一

来源:互联网 发布:迷糊娃娃淘宝价 编辑:程序博客网 时间:2024/06/07 01:13

activity_main.xml

<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" >    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentBottom="true"        android:layout_centerHorizontal="true"        android:text="下载网络图片" />    <ImageView        android:id="@+id/imageView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_centerVertical="true"        android:src="@drawable/ic_launcher" /></RelativeLayout>


 

添加网络访问权限

 <uses-permission android:name="android.permission.INTERNET" />


MainActivity

package com.example.android_asytask_download;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import android.os.AsyncTask;import android.os.Bundle;import android.app.Activity;import android.app.ProgressDialog;import android.content.Entity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.view.Menu;import android.view.View;import android.widget.Button;import android.widget.ImageView;public class MainActivity extends Activity {private Button button;private ImageView imageView;private ProgressDialog progressDialog;private String image_path = "http://a.hiphotos.baidu.com/image/w%3D2048/sign=7610c70c5143fbf2c52ca1238446cb80/d4628535e5dde71120a3a1f2a5efce1b9d166145.jpg";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button = (Button) this.findViewById(R.id.button1);imageView = (ImageView) this.findViewById(R.id.imageView1);progressDialog=new ProgressDialog(this);progressDialog.setTitle("提示");progressDialog.setMessage("正在下载,请稍后...");button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubnew myTask().execute(image_path);//执行异步任务操作}});}/** * 使用异步任务规则 1.声明一个类继承AsyncTask类 * 2.第一个参数表示要执行的任务通常是网络的路径,第二参数表示刻度,第三个参数表示执行返回的结果 * */public class myTask extends AsyncTask<String, Void, Bitmap> {// 表示任务之前操作@Overrideprotected void onPreExecute() {// TODO Auto-generated method stubprogressDialog.show();super.onPreExecute();}// 表示耗时操作@Overrideprotected Bitmap doInBackground(String... params) {// TODO Auto-generated method stubBitmap bitmap=null;HttpClient httpClient=new DefaultHttpClient();HttpGet httpGet=new HttpGet(params[0]);try {HttpResponse httpResponse=httpClient.execute(httpGet);if(httpResponse.getStatusLine().getStatusCode()==200){HttpEntity httpEntity=httpResponse.getEntity();byte[]data=EntityUtils.toByteArray(httpEntity);bitmap=BitmapFactory.decodeByteArray(data, 0, data.length);}} catch (Exception e) {// TODO: handle exception};return bitmap;}// 表示更新ui操作@Overrideprotected void onPostExecute(Bitmap result) {// TODO Auto-generated method stubimageView.setImageBitmap(result);progressDialog.dismiss();super.onPostExecute(result);}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}


1.异步任务相当于一个线程的框架,内部封装了Thread,Handler,所以使用异步任务代码中不需要开启一个线程,一般较短的耗时时候使用异步任务。

2.Ui主线程不能直接访问网络,否则会出android.os.NetworkOnMainThreadException异常。

0 0
原创粉丝点击