入门android异步任务之AsyncTask(以加载网络图片为例子)
示例最终效果图:
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.lesson" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="7" /> <!-- 用于访问网络的授权 --> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.lesson.MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
基本布局文件activity_main.xml:一个ImageView和一个Button
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="48dp"/> <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="下载图片" /> </RelativeLayout>
MainActivity.java
/* * 异步任务实现activity中加载网络图片 */ package com.lesson; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.test.AndroidTestCase; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { private Button button; private ProgressDialog progerssDialog; private ImageView imageView;//要加载的图片 private final String url="http://www.windows7en.com/desk/UploadFiles_7433/201006/2010060910062279.jpg"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_main); button=(Button)findViewById(R.id.button1); imageView=(ImageView)findViewById(R.id.imageView1); progerssDialog=new ProgressDialog(this); progerssDialog.setCancelable(false); //设置进度条水平加载 progerssDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { //异步任务调用 new ImageUpdate().execute(url); } }); } class ImageUpdate extends AsyncTask<String, Integer,byte[]>{ //线程启动时,该方法被调用次序:2 @Override protected byte[] doInBackground(String... arg0) { HttpGet httpGet=new HttpGet(arg0[0]); InputStream inputStream=null; byte[] result=null; byte[] data=new byte[1024]; HttpClient client = new DefaultHttpClient(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { HttpResponse httpResponse=client.execute(httpGet);//得到响应 if(httpResponse.getStatusLine().getStatusCode()==200){ inputStream=httpResponse.getEntity().getContent(); //文件总长度 int filelenth=(int) httpResponse.getEntity().getContentLength(); int readlength=0; int totallenth=0; while((readlength=inputStream.read(data))!=-1){ totallenth+=readlength; //用于进度条刻度计算公式 int progressValue= (int)((totallenth/(float)filelenth)*100); //将刻度值传递到第2步 publishProgress(progressValue); outputStream.write(data, 0, readlength); } result=outputStream.toByteArray(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ client.getConnectionManager().shutdown(); } return result; } //线程启动时,该方法被调用次序:4 @Override protected void onPostExecute(byte[] result) { // TODO Auto-generated method stub super.onPostExecute(result); Bitmap bitmap=BitmapFactory.decodeByteArray(result, 0, result.length); imageView.setImageBitmap(bitmap); progerssDialog.dismiss(); } //线程启动时,该方法被调用次序:1 @Override protected void onPreExecute() { super.onPreExecute(); //加载图片时的进度显示对话框 progerssDialog.show(); } //线程启动时,该方法被调用次序:3 @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); progerssDialog.setProgress(values[0]); } } }
相关推荐
dxyadc 2019-12-24
Miryou 2013-07-04
omguare 2011-08-11
luoj 2011-05-24
老菜鸟自习室 2011-05-23
ustcrding 2011-04-23
TTHHVV 2011-09-28
sgafdsg 2011-09-21
TTHHVV 2011-09-17
Helene 2011-09-17
ustcrding 2011-09-17
best0power 2015-03-16
椎锋陷陈 2012-06-07
Android进阶 2019-06-26
猫耳山在天边 2019-06-26
wxuande 2019-06-21
AndroidGA 2017-03-20
housezhu 2015-03-16
西木 2015-03-05