现在的位置: 首页 > 综合 > 正文

异步获取网络图片

2013年10月01日 ⁄ 综合 ⁄ 共 8339字 ⁄ 字号 评论关闭

方式一:使用Handler、Thread/Runnable 、URL、HttpURLConnection等等来进行异步下载网络图片。

方式二: 那么有没有比较更好好的实现方式呢?这个可以有!它就是AsyncTaskAsyncTask的特点是任务在主UI线程之外运行,而回调方法是在主UI线程中,这就有效地避免了使用Handler带来的麻烦。
方式三:

java.util.concurrent 是在并发编程中很常用的实用工具类。

ExecutorService类:具有服务生命周期的Executors。

Executors 类:执行器,将为你管理Thread 对象。

我们知道这些是用来处理并发任务的,当然我们Demo只是请求一张图片而已,并不能体现并发,但是假设我们有一个ListView,里面每一项都需要一张网络图片显示呢?那么并发性就可以体现出来了:多个线程并发从网络下载图片。当然这个版本不会使用listView显示多个项图片,以后做个版本吧!研究下。

 思路是这样的:

1:动态的创建N个线程,防在线程池中。

2:系统从线程池中取出一个线程投入执行,线程池中若没有线程可用,其他任务只有先等待了,直到有新线程释放,才调用。

如下有几个方法可以动态的指定多少个线程。

package com.shao.image;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class ImageDownLoadActivity extends Activity implements OnClickListener{
    private static final String params="http://blog.ce.cn/sp1/blog_attachments/image_2008/04/10183110294.jpg";
    private Button btnFirst,btnSecond,btnThree;
    private ProgressBar progress;
    private FrameLayout frameLayout;
    private Bitmap bitmap=null;
    ProgressDialog dialog=null;
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        btnFirst=(Button)this.findViewById(R.id.btnFirst);
        btnSecond=(Button)this.findViewById(R.id.btnSecond);
        btnThree=(Button)this.findViewById(R.id.btnThree);
        progress=(ProgressBar)this.findViewById(R.id.progress);
        progress.setVisibility(View.GONE);
        frameLayout=(FrameLayout)this.findViewById(R.id.frameLayout);
        
        btnFirst.setOnClickListener(this);
        btnSecond.setOnClickListener(this);  
        btnThree.setOnClickListener(this);  
    }

  //前台ui线程在显示ProgressDialog,
    //后台线程在下载数据,数据下载完毕,关闭进度框
    @Override
    public void onClick(View view) {
        switch(view.getId()){
        case R.id.btnFirst:
            System.out.println("open");
            dialog = ProgressDialog.show(this, "",
                    "下载数据,请稍等 …", true, true);
            //启动一个后台线程
            handler.post(new Runnable(){
                @Override
                public void run() {
                     //这里下载数据
                    try{
                        URL  url = new URL(params);
                        HttpURLConnection conn  = (HttpURLConnection)url.openConnection();
                        conn.setDoInput(true);
                        conn.connect();
                        InputStream inputStream=conn.getInputStream();
                        bitmap = BitmapFactory.decodeStream(inputStream);
                        Message msg=new Message();
                        msg.what=1;
                        System.out.println("11111111111111");
                        handler.sendMessage(msg);
                     
                    } catch (MalformedURLException e1) {
                        e1.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }  
                }
            });
            break;
        case R.id.btnSecond:
            MyASyncTask yncTask=new MyASyncTask(this,frameLayout);
               yncTask.execute(params);
               break;
        case R.id.btnThree:
            System.out.println("start");
             progress.setVisibility(View.VISIBLE);
             final Handler newhandler=new Handler();
             ExecutorService  executorService=Executors.newFixedThreadPool(1);
           //  executorService.execute(command)
             executorService.execute(new Runnable(){
                 @Override
                 public void run() {
                     try {
                         URL newurl = new URL(params);
                         HttpURLConnection conn = (HttpURLConnection)newurl.openConnection();
                         conn.setDoInput(true);
                         conn.connect();
                         InputStream inputStream=conn.getInputStream();
                         bitmap = BitmapFactory.decodeStream(inputStream);
                         newhandler.post(new Runnable(){
                             @Override
                             public void run() {
                                 ImageView view=(ImageView)frameLayout.findViewById(R.id.image);
                                
                                 view.setImageBitmap(bitmap);
                             }
                         });
                     } catch (MalformedURLException e) {
                         e.printStackTrace();
                     } catch (IOException e) {
                         e.printStackTrace();
                     }
                 }
                 
             });
             progress.setVisibility(View.GONE);
             break;
        }
         
    }
     /**这里重写handleMessage方法,接受到子线程数据后更新UI**/
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg){
            switch(msg.what){
            case 1:
                //关闭
                ImageView view=(ImageView)frameLayout.findViewById(R.id.image);
                view.setImageBitmap(bitmap);
                System.out.println("close");
                dialog.dismiss();
                break;
            }
        }
    };

}

package com.shao.image;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class MyASyncTask extends AsyncTask<String, Integer, Bitmap> {
    Context context;
    FrameLayout frameLayout;
public MyASyncTask(Context context,FrameLayout frameLayout) {
    this.context = context;
    this.frameLayout = frameLayout;
}
    @Override
    protected Bitmap doInBackground(String... params) {
        Bitmap bitmap=null;
        try {
            
            URL url = new URL(params[0]);
            HttpURLConnection con=(HttpURLConnection) url.openConnection();
            con.setDoInput(true);
            con.connect();
            InputStream inputStream=con.getInputStream();
            
            bitmap=BitmapFactory.decodeStream(inputStream);
            inputStream.close();
        }
         catch (MalformedURLException e) {
                e.printStackTrace();
            }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bitmap;
    }
    //执行获得图片数据后,更新UI:显示图片,隐藏进度条
    @Override
    protected void onPostExecute(Bitmap Result){
     ImageView imgView=(ImageView)frameLayout.findViewById(R.id.image);
        imgView.setImageBitmap(Result);
        ProgressBar bar=(ProgressBar)frameLayout.findViewById(R.id.progress);
        bar.setVisibility(View.GONE);
    }
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button
      android:id="@+id/btnFirst"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="异步下载方式一"
     >
    </Button>
    
    <Button
      android:id="@+id/btnSecond"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="异步下载方式二"
     >
    </Button>
     <Button
      android:id="@+id/btnThree"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="异步下载方式三"
     >
    </Button>
 
    <FrameLayout
     android:layout_width="fill_parent"
     android:layout_height="match_parent"
     android:id="@+id/frameLayout"
    >
    
   <ImageView
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="centerInside"
    android:padding="2dp"
    >
   </ImageView>
    
    <ProgressBar
     android:id="@+id/progress"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_gravity="center">
  </ProgressBar>
    
  </FrameLayout>
</LinearLayout>

抱歉!评论已关闭.