歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android通過http協議獲得圖片

Android通過http協議獲得圖片

日期:2017/3/1 9:57:05   编辑:Linux編程

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);}

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved