传播智客学习笔记--L23 从网络获取图片
如何通过字节数据得到图片
protected void showImg() { String path = editText.getText().toString(); byte[] data = ImageService.getImage(path);//自定义业务类 Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);//通过字节数组得到图片 imgView.setImageBitmap(bm);//设置ImageView的图片 }
如何通过网络获得数据
1 public class ImageService { 2 3 public static byte[] getImage(String path) throws Exception { 4 URL url = new URL(path); 5 6 HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 7 conn.setConnectTimeout(5000);//设置超时时间 8 conn.setRequestMethod("GET");//设置访问方式 9 if(conn.getResponseCode() == 200){ 10 InputStream inputstream = conn.getInputStream();//从服务器得到输入流 11 /** 12 * 读取输入流中数据,可以写为一个工具类 13 */ 14 byte[] buffer = new byte[1024]; 15 ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); 16 int len = 0; 17 while( (len = inputstream.read(buffer)) != -1 ){ 18 byteOs.write(buffer, 0, buffer.length); 19 } 20 inputstream.close(); 21 return byteOs.toByteArray(); 22 } 23 return null; 24 } 25 26 }
获取相关权限
<uses-permission android:name="android.permission.INTERNET"/>
但是做到这里,会出错!!
-
从安卓2.3 以后禁止在UI主线程中执行网络操作
-
必须新建WorkerThread从网络中得到数据
-
注意:不能在WorkerThread中直接改变UI中的控件,只能将数据传递给主线程
-
可以通过Handler类通过消息机制在主线程中处理数据
1 public class MainActivity extends Activity { 2 private EditText editText; 3 private ImageView imgView; 4 private Handler handler; 5 6 @Override 7 protected void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 setContentView(R.layout.activity_main); 10 11 editText = (EditText)findViewById(R.id.website); 12 imgView = (ImageView)findViewById(R.id.imageView); 13 14 //点击Button,获取网络中图片的数据 15 //涉及网络操作,必须新建WorkerThread处理相关业务 16 //WorkerThread中不能改变UI主线程 17 //UI主线程必须提供相应的处理方法Handler的实例对象中的相关方法 18 Button btn = (Button)findViewById(R.id.btnFind); 19 btn.setOnClickListener(new OnClickListener() { 20 @Override 21 public void onClick(View v) { 22 Thread networkThread = new Thread(new NetworkThread()); 23 networkThread.start(); 24 } 25 }); 26 27 handler = new Handler(){ 28 @Override 29 public void handleMessage(Message msg) { 30 byte[] data = (byte[])msg.obj; 31 Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);//通过字节数组得到图片 32 imgView.setImageBitmap(bm);//设置ImageView的图片 33 } 34 }; 35 } 36 37 private class NetworkThread implements Runnable{ 38 @Override 39 public void run() { 40 String path = editText.getText().toString(); 41 42 try { 43 byte[] data = ImageService.getImage(path);//自定义业务类 44 Message msg = handler.obtainMessage(); 45 msg.obj = data; 46 handler.sendMessage(msg); 47 } catch (Exception e) { 48 e.printStackTrace(); 49 } 50 51 } 52 }