异步任务加载网络图片

来源:互联网 发布:java空指针异常处理 编辑:程序博客网 时间:2024/06/05 08:32

android异步任务之AsyncTask(以加载网络图片替例子)

2016-05-14 07:50 | 986人阅读 | 来源
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";@Overrideprotected 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() {@Overridepublic void onClick(View arg0) {//异步任务调用new ImageUpdate().execute(url);}});}class ImageUpdate extends AsyncTask<String, Integer,byte[]>{//线程启动时,该方法被调用次序:2@Overrideprotected 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]); } } }
0 0
原创粉丝点击