Android通过http协议获得图片


Android通过图片网址获得图片并显示在imageView中。

下面就简单的来说明操作过程:

首先必须在布局文件中声明imageView控件:

  1. <ImageView
  2. android:id="@+id/image"
  3. android:layout_width="fill_parent"
  4. android:layout_height="wrap_content"/>

还必须在清单文件中加入访问网络的权限:

<uses-permission android:name="android.permission.INTERNET" />

其次:用一个service类来实现访问http协议,并且获得链接的返回值这个过程:htmlPath是图片的网络地址

  1. public class PageService {
  2. /**@description:获取图片的数据
  3. * @author:Administrator
  4. * @return:byte[]
  5. * @param htmlpath
  6. * @return
  7. * @throws Exception
  8. */
  9. public static byte[] getImage(String htmlpath) throws Exception {
  10. byte[] imagearray = null;
  11. URL url = new URL(htmlpath);
  12. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  13. conn.setConnectTimeout(5000);
  14. // conn.setRequestMethod("GET");
  15. conn.connect();
  16. if (conn.getResponseCode() == 200) {
  17. byte[] buffer = new byte[1024];
  18. ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
  19. int len = 0;
  20. InputStream inputStream = conn.getInputStream();
  21. while ((len = inputStream.read(buffer)) != -1) {
  22. arrayOutputStream.write(buffer, 0, buffer.length);
  23. }
  24. imagearray = arrayOutputStream.toByteArray();
  25. }
  26. return imagearray;
  27. }
  28. }

最后在activity中启用一个线程来调用这个业务方法,并在handler中对UI进行更新:(必须实现线程否则会出错,这是和3.0版本之前不同的地方)

  1. public class MainActivity extends Activity {
  2. private EditText strpath;
  3. private TextView htmlcontent;
  4. private ImageView imageview;
  5. Handler handler=new Handler(){
  6. @Override
  7. public void handleMessage(Message msg) {
  8. byte[] data=(byte[])msg.obj;
  9. Bitmap image=BitmapFactory.decodeByteArray(data, 0, data.length);
  10. imageview.setImageBitmap(image);}

  • 1
  • 2
  • 下一页

相关内容

    暂无相关文章