zoukankan      html  css  js  c++  java
  • AsyncTask实现下载图片

    实现效果:

    /*采用异步任务  AsyncTask<String,Integer, byte[]>
      * 参数一代表 执行异步任务时传递的参数的类型
      * 参数二 如果不采用进度,则填Void,否则填 Integer
      * 参数三 是指网络回传回来的数据类型
      */

    客户端代码:

    MainActivity.java

      1 package com.example.load_jpg;
      2 
      3 import java.io.ByteArrayOutputStream;
      4 import java.io.InputStream;
      5 
      6 import org.apache.http.HttpResponse;
      7 import org.apache.http.client.HttpClient;
      8 import org.apache.http.client.methods.HttpGet;
      9 import org.apache.http.impl.client.DefaultHttpClient;
     10 
     11 import android.app.Activity;
     12 import android.app.ProgressDialog;
     13 import android.content.Context;
     14 import android.graphics.Bitmap;
     15 import android.graphics.BitmapFactory;
     16 import android.os.AsyncTask;
     17 import android.os.Bundle;
     18 import android.view.View;
     19 import android.view.View.OnClickListener;
     20 import android.widget.Button;
     21 import android.widget.ImageView;
     22 import android.widget.Toast;
     23 
     24 public class MainActivity extends Activity {
     25 
     26     
     27     private ProgressDialog dialog;
     28     private ImageView iv;
     29     private Button btn;
     30     private final  static  String PATH="http://172.16.30.146:8080/Phone/a10.jpg";
     31     private Context context;
     32     
     33     @Override
     34     protected void onCreate(Bundle savedInstanceState) {
     35         super.onCreate(savedInstanceState);
     36         setContentView(R.layout.activity_main);
     37         context = this;
     38         init();
     39         btn.setOnClickListener(new OnClickListener() {
     40             @Override
     41             public void onClick(View v) {
     42                 new MyTask().execute(PATH);//执行异步任务
     43             }
     44         });
     45     }
     46     private void init() {
     47         iv  =(ImageView) findViewById(R.id.image);
     48         btn = (Button) findViewById(R.id.btn);
     49         dialog = new ProgressDialog(context);
     50         dialog.setCancelable(true);
     51         dialog.setTitle("提醒");
     52         dialog.setMessage("正在下载中...");
     53         dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
     54     }
     55 
     56     public class MyTask extends AsyncTask<String, Integer, byte[]>{
     57 
     58         @Override
     59         protected void onPreExecute() {//在异步符务执行之前 这个方法会被执行
     60             dialog.show();
     61             super.onPreExecute();
     62         }
     63         
     64         @Override
     65         protected byte[] doInBackground(String... params) {
     66             HttpClient httpClient = new DefaultHttpClient();
     67             HttpGet httpGet = new HttpGet(params[0]);
     68             
     69             InputStream is = null;
     70             ByteArrayOutputStream bos =new ByteArrayOutputStream();
     71             
     72             try {
     73                 HttpResponse httpResponse = httpClient.execute(httpGet);//执行path
     74                 if(httpResponse.getStatusLine().getStatusCode()==200){
     75                     is = httpResponse.getEntity().getContent();
     76                     
     77                     long total_length = httpResponse.getEntity().getContentLength();
     78                     int current_length = 0;
     79                     byte[] tmp = new byte[1024];
     80                     int len;
     81                     while((len=is.read(tmp))!=-1){
     82                         current_length+=len;
     83                         int update = (int)((float)current_length/total_length*100);
     84                         publishProgress(update);
     85                         bos.write(tmp, 0, len);
     86                     }
     87                     return bos.toByteArray();
     88                     
     89                 }
     90             } catch (Exception e) {
     91                 
     92             }finally{
     93                 httpClient.getConnectionManager().shutdown();
     94             }
     95             
     96             return null;
     97         }
     98         
     99         @Override
    100         protected void onProgressUpdate(Integer... values) {
    101             dialog.setProgress(values[0]);
    102             super.onProgressUpdate(values);
    103         }
    104         
    105         @Override
    106         protected void onPostExecute(byte[] result) {
    107             if(result!=null){
    108                 Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
    109                 iv.setImageBitmap(bitmap);
    110                 Toast.makeText(context, "下载成功", Toast.LENGTH_LONG).show();
    111             }else{
    112                 Toast.makeText(context, "下载失败", Toast.LENGTH_LONG).show();
    113             }
    114             dialog.dismiss();
    115             super.onPostExecute(result);
    116         }
    117         
    118     }
    119 
    120 }


    activity_main.xml

     1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     2     xmlns:tools="http://schemas.android.com/tools"
     3     android:layout_width="match_parent"
     4     android:layout_height="match_parent"
     5    android:orientation="vertical"
     6     tools:context=".LoadPicActivity" >
     7 
     8     
     9     <ImageView
    10         android:id="@+id/image"
    11         android:layout_width="300dp"
    12         android:layout_height="300dp"
    13         android:src="@drawable/ic_launcher"
    14         />
    15     
    16  <Button 
    17      android:id="@+id/btn"
    18        android:layout_width="match_parent"
    19         android:layout_height="wrap_content"
    20         android:text="下载"
    21      
    22      />
    23 </LinearLayout>


    服务器端:建立web project,放入图片即可

    最后在清单里注册:<uses-permission android:name="android.permission.INTERNET"/>

  • 相关阅读:
    如何快速方便的输出向量vector容器中不重复的内容
    System.IO.FileInfo.cs
    System.IO.FileSystemInfo.cs
    System.IO.FileAttributes.cs
    System.IO.StreamWriter.cs
    System.IO.TextWriter.cs
    System.IO.StreamReader.cs
    System.IO.FileStream.cs
    System.IO.FileOptions.cs
    System.IO.FileShare.cs
  • 原文地址:https://www.cnblogs.com/UniqueColor/p/5278977.html
Copyright © 2011-2022 走看看