Android入门之网络图片查看器

package com.xsx.image;

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

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
 protected static final int CHANGE_UI = 1;
 protected static final int ERROR = 2;
 private EditText et_address;
 private ImageView iv_show;
 
 
 
 //1、在主线程建立消息处理器
 
 private Handler handler = new Handler(){
  public void handleMessage(android.os.Message msg){
   if(msg.what==CHANGE_UI){
    Bitmap bitmap = (Bitmap) msg.obj;
    iv_show.setImageBitmap(bitmap);
   }else if(msg.what==ERROR){
    Toast.makeText(MainActivity.this, "显示图片失败", 0).show();
   }
  };
 };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        et_address = (EditText) findViewById(R.id.et_address);
        iv_show = (ImageView) findViewById(R.id.iv_image);
    }
   
    public void click(View view){
     final String path = et_address.getText().toString().trim();
     if(TextUtils.isEmpty(path)){
      Toast.makeText(this, "图片地址不能为空", 0).show();
     }else{
      new Thread(){
       public void run(){

           //链接服务器get请求获取图片
           try{
            URL url = new URL(path);
            //根据url发送http请求
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");//设置请求方式
            conn.setConnectTimeout(5000);
//            conn.setReadTimeout(10000);
//            conn.setRequestProperty(field, newValue);
            
            //得到服务器返回的响应码
            int code = conn.getResponseCode();
            if(code==200){
             InputStream is = conn.getInputStream();
             Bitmap bitmap = BitmapFactory.decodeStream(is);
//             iv_show.setImageBitmap(bitmap);
             Message msg = new Message();
             msg.what = CHANGE_UI;
             
             msg.obj = bitmap;
             handler.sendMessage(msg);
            }else{
             Message msg = new Message();
             msg.what = ERROR;
             handler.sendMessage(msg);
            }
           }catch (Exception e){
            e.printStackTrace();
            Message msg = new Message();
         msg.what = ERROR;
         handler.sendMessage(msg);
           }
       }
      }.start();
     }
    }
}
Android入门之网络图片查看器

你可能感兴趣的:(Android入门之网络图片查看器)