标签:
import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuItem; 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 String TAG = "MainActivity"; ImageView image = null; EditText edit = null; Handler handler = new Handler(){ //接收一个消息 @Override public void handleMessage(Message msg) { super.handleMessage(msg); if(msg.what == 1) { Bitmap bitmap = (Bitmap) msg.obj; image.setImageBitmap(bitmap); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); image = (ImageView) findViewById(R.id.img); edit = (EditText) findViewById(R.id.et_net); Button button = (Button) findViewById(R.id.bt_get); button.setOnClickListener(this); } /** * 1.访问网络不能直接放在主方法里面(android.os.NetworkOnMainThreadException),应该放在一个线程里面 * 2. android.view.ViewRootImpl$CalledFromWrongThreadException: 只能在主线程或者UI线程里面修改视图,应该用通信来解决 * */ @Override public void onClick(View v) { final String uri = edit.getText().toString(); //拿到图片的网络地址 new Thread(new Runnable() { @Override public void run() { Bitmap bitmap = getImageFromNet(uri); if(null != bitmap) { Message msg = new Message(); msg.what = 1; //你是谁 msg.obj = bitmap; handler.sendMessage(msg); //发送一个消息 //image.setImageBitmap(bitmap); Log.i(TAG, "========" + bitmap); }else { //Toast.makeText(MainActivity.this, "获取图片失败", 0).show(); } } }).start(); } //返回的不是image了 返回的是bitmap >> 位图 public Bitmap getImageFromNet(String uri) { HttpURLConnection conn = null; try { //1.首先将地址转换为Uri //Uri net_uri = Uri.parse(uri); //这种方式是错误的 URL url = new URL(uri); //2. 获取网络连接 conn = (HttpURLConnection) url.openConnection(); //这个地方要转换一次,转换为你获取图片的协议连接 //3. 设置请求的一些常用的参数 conn.setConnectTimeout(30000);//设置超时 conn.setDoInput(true); //设置请求可以放服务器写入数据 conn.setReadTimeout(30000); //设置连接去读取数据的超时时间 //4.真正请求图片,然后把从网络上请求到的二进制流保存到了inputStream里面 conn.connect(); InputStream in = conn.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(in); //BitMap的图片工厂,创建出一个图片 //5. 关闭连接 return bitmap; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { //5. 关闭连接 if(null != conn) { conn.disconnect(); } } return null; } }
标签:
原文地址:http://www.cnblogs.com/labixiaoxin/p/4932670.html