handler从网络获取图片

来源:互联网 发布:小说采集网站源码 编辑:程序博客网 时间:2024/05/17 06:24
package com.smalltown.day18_handlerimag;

import com.smalltown.day18_handlerimag.utils.HttpUtils;

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.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
    
    private ImageView iv;
    
    private static final String imagPath = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superplus/img/logo_white_ee663702.png";

    private ProgressDialog progressDialog;
    
    private static  final  int  OK = 1;
    private static  final  int  ERROR = OK+1;
    
    
    
    private Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            
            switch (msg.what) {
            case OK:
                Bitmap bp = (Bitmap) msg.obj;
                iv.setImageBitmap(bp);
                break;
            case ERROR:
                String str = (String) msg.obj;
                Toast.makeText(MainActivity.this, str, 0).show();
                break;

            default:
                break;
            }
            
            progressDialog.dismiss();
        };
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        iv = (ImageView) findViewById(R.id.iv);
        
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("正在下载数据");
    }

    //点击按钮下载图片
    public void OnclickBtn(View v){
        
        
        
        switch (v.getId()) {
        case R.id.btn:
            
            progressDialog.show();
            
            new Thread(){
                public void run() {
                    if(HttpUtils.isNetWork(MainActivity.this)){
                        byte[] buffer = HttpUtils.getData(imagPath);
                        if(buffer!=null && buffer.length>0){
                            Bitmap bp = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
                            Message msg = handler.obtainMessage();
                            msg.obj = bp;
                            msg.what  = OK;//下载成功
                            handler.sendMessage(msg);
                        }
                    }else{
                        //无网络
                        Message msg = handler.obtainMessage();
                        msg.obj = "网络异常,请检测";
                        msg.what  = ERROR;//下载失败
                        handler.sendMessage(msg);
                        
                    }
                    
                };
                
            }.start();
        
            
            break;

        default:
            break;
        }
        
    }


}





package com.smalltown.day18_handlerimag.utils;

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.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class HttpUtils {
    /**
     * 判断是否有网络
     * @param context
     * @return
     */
    public static boolean isNetWork(Context context){
        //得到网络的管理者
        ConnectivityManager manager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        
        if(info!=null){
            return true;
                    
        }else{
            return false;
        }
        
    }

    
    /**
     * 获取数据
     * @param path
     * @return
     */
    public static byte[] getData(String path) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(path);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                InputStream inputStream = response.getEntity().getContent();
                byte[] buffer = new byte[1024];
                int temp = 0;
                while ((temp = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, temp);
                    outputStream.flush();
                }

            }
            return outputStream.toByteArray();

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;

    }

}


布局文件



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

    <ImageView
        android:id="@+id/iv"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="#ff00ff"
        android:layout_centerInParent="true"
        android:src="@drawable/ic_launcher"
         />
    
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:onClick="OnclickBtn"
        android:text="下载图片"
        
        />

</RelativeLayout>


0 0
原创粉丝点击