AsyncTask异步二

来源:互联网 发布:linux使用编辑器 编辑:程序博客网 时间:2024/06/05 20:51

activity_main

<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>


 

MainActivity

package com.example.android_asytask_download;import java.io.ByteArrayOutputStream;import java.io.InputStream;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.R.integer;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("正在下载,请稍后...");progressDialog.setProgressStyle(progressDialog.STYLE_HORIZONTAL);// 设置进度条样式progressDialog.setCancelable(false);// 点击不会失去焦点,直到下载结束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, Integer, Bitmap> {// 表示任务之前操作@Overrideprotected void onPreExecute() {// TODO Auto-generated method stubprogressDialog.show();super.onPreExecute();}// 表示耗时操作@Overrideprotected Bitmap doInBackground(String... params) {// TODO Auto-generated method stubBitmap bitmap = null;ByteArrayOutputStream outputStream = new ByteArrayOutputStream();// 图片读取放到内存缓冲区中InputStream inputStream = null;HttpClient httpClient = new DefaultHttpClient();HttpGet httpGet = new HttpGet(params[0]);try {HttpResponse httpResponse = httpClient.execute(httpGet);if (httpResponse.getStatusLine().getStatusCode() == 200) {inputStream = httpResponse.getEntity().getContent();// 获取文件长度long file_leagth = httpResponse.getEntity().getContentLength();int len = 0;byte[] date = new byte[1024];// 每次读取长度int total_leagth = 0;// 已经下载的总长度while ((len = inputStream.read(date)) != -1) {total_leagth += len;int value = (int) ((total_leagth / (float) file_leagth) * 100);publishProgress(value);outputStream.write(date, 0, len);}byte[]temp=outputStream.toByteArray();bitmap=BitmapFactory.decodeByteArray(temp, 0, temp.length);}} catch (Exception e) {// TODO: handle exception} finally {if (inputStream != null) {try {inputStream.close();} catch (Exception e2) {// TODO: handle exception}}}return bitmap;}@Overrideprotected void onProgressUpdate(Integer... values) {// TODO Auto-generated method stubsuper.onProgressUpdate(values);progressDialog.setProgress(values[0]);//进度更新};// 表示更新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;}}


0 0
原创粉丝点击