package org.xml.demo.html; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import ogg.huanxin.huadong.R; import android.annotation.SuppressLint; 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.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; public class MainHtml extends Activity { private ImageView imageView; private Button button; // 此方法在主线程中调用,可以用来刷新ui @SuppressLint("HandlerLeak") Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { // 处理消息时,需要知道到底是成功消息还是失败消息 switch (msg.what) { case 1: // 把位图对象显示至imageview中 imageView.setImageBitmap((Bitmap) msg.obj); break; case 0: Toast.makeText(MainHtml.this, "请求失败", Toast.LENGTH_SHORT) .show(); break; default: break; } }; }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); super.setContentView(R.layout.mainhtml); button = (Button) findViewById(R.id.bb_html_click); imageView = (ImageView) findViewById(R.id.iv_html_image); button.setOnClickListener(new MyOnclick()); } private class MyOnclick implements View.OnClickListener { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Thread t = new Thread() { @Override public void run() { // TODO Auto-generated method stub // 1 确认网址 String path = "http://192.168.56.1:8080/a.jpg"; try { // 2 把网址封装成一个url对象 URL url = new URL(path); // 3 获取客户端和服务器的连接对象,此时还没有建立连接 HttpURLConnection conn = (HttpURLConnection) url .openConnection(); // 4 对连接对象进行初始化 // 设置请求方式 注意大写 conn.setRequestMethod("GET"); // 设置连接超时 conn.setConnectTimeout(5000); // 设置读取超时 conn.setReadTimeout(5000); // 5 发送请求 , 与服务器建立连接 conn.connect(); // 如果反应码为200, 则说明请求成功 if (conn.getResponseCode() == 200) { // 获取服务器响应头中的流,流里的数据就是客户端请求的数据 InputStream is = conn.getInputStream(); // 读出流中的数据,并构造成位图对象 Bitmap bm = BitmapFactory.decodeStream(is); // 把位图对象显示至imageview Message msg = handler.obtainMessage(); // 消息对象携带数据 msg.obj = bm; msg.what = 1; // 把消息发送至主线程的消息队列 handler.sendMessage(msg); } else { Message msg = handler.obtainMessage(); msg.what = 0; handler.sendMessage(msg); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; t.start(); } } }
时间: 2024-11-08 02:19:17