package com.example.internetimageview; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import javax.net.ssl.HttpsURLConnection; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener { protected static final int CHANG_UI = 1; protected static final int SHOW_MSG = 2; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == CHANG_UI){ Bitmap bm = (Bitmap) msg.obj; iv_image.setImageBitmap(bm); }else if(msg.what == SHOW_MSG){ Toast.makeText(MainActivity.this, msg.obj.toString(), 0).show(); } } }; private Button bt_show = null; private EditText et_url = null; private ImageView iv_image = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt_show = (Button) findViewById(R.id.bt_show); et_url = (EditText) findViewById(R.id.et_url); iv_image = (ImageView) findViewById(R.id.iv_image); bt_show.setOnClickListener(this); et_url.setText("http://www.baidu.com/img/baidu_jgylogo3.gif"); } @Override public void onClick(View v) { new Thread(){ @Override public void run() { //Looper.prepare(); String path = et_url.getText().toString(); if (TextUtils.isEmpty(path)){ showMsg("图片路径不能为空"); return; } try { URL url = new URL(path); HttpURLConnection conn= (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); //必须大写 conn.setConnectTimeout(5000); conn.setReadTimeout(5000); int responseCode= conn.getResponseCode(); //显示响应状态码 showMsg(responseCode + ""); if (responseCode == 200){ InputStream is = conn.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(is); Message message = new Message(); message.what = CHANG_UI; message.obj = bitmap; handler.handleMessage(message); // 第二种方法 // Looper.prepare(); // iv_image.setImageBitmap(bitmap); // Looper.loop(); }else{ showMsg("图片响应失败"); } }catch(MalformedURLException e){ showMsg("图片路径可能错误"); }catch (IOException e) { e.printStackTrace(); showMsg("图片IO失败"); } catch (Exception e) { e.printStackTrace(); showMsg("图片获取失败"); } } /**显示消息 * @param msg 要显示的消息文本 */ private void showMsg(CharSequence msg){ Message message = new Message(); message.what = SHOW_MSG; message.obj = msg; handler.handleMessage(message); } }.start(); } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)