歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android實現網絡圖片查看器和網頁源碼查看器

Android實現網絡圖片查看器和網頁源碼查看器

日期:2017/3/1 11:17:33   编辑:Linux編程

網絡圖片查看器

清單文加入網絡訪問權限:

  1. |<!-- 訪問internet權限 -->
  2. <uses-permission Android:name="android.permission.INTERNET"/>

界面如下:

示例:

  1. public class MainActivity extends Activity {
  2. private EditText imagepath;
  3. private ImageView imageView;
  4. @Override
  5. public void onCreate(Bundle savedInstanceState) {
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.main);
  8. imagepath = (EditText) this.findViewById(R.id.imagepath);
  9. imageView = (ImageView) this.findViewById(R.id.imageView);
  10. Button button = (Button) this.findViewById(R.id.button);
  11. button.setOnClickListener(new View.OnClickListener() {
  12. public void onClick(View v) {
  13. String path = imagepath.getText().toString();
  14. try{
  15. byte[] data = ImageService.getImage(path);//獲取圖片數據
  16. if(data!=null){
  17. //構建位圖對象
  18. Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
  19. imageView.setImageBitmap(bitmap);//顯示圖片
  20. }else{
  21. Toast.makeText(getApplicationContext(), R.string.error, 1).show();
  22. }
  23. }catch (Exception e) {
  24. Toast.makeText(getApplicationContext(), R.string.error, 1).show();
  25. }
  26. }
  27. });
  28. }
  29. }
  1. public class ImageService {
  2. /**
  3. * 獲取圖片
  4. * @param path 網絡圖片路徑
  5. * @return 圖片的字節數據
  6. */
  7. public static byte[] getImage(String path) throws Exception{
  8. URL url = new URL(path);
  9. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  10. //設置超時時間
  11. conn.setConnectTimeout(5000);
  12. conn.setRequestMethod("GET");
  13. if(conn.getResponseCode()==200){
  14. InputStream inStream = conn.getInputStream();
  15. byte[] data = StreamTool.read(inStream);
  16. return data;
  17. }
  18. return null;
  19. }
  20. }
  1. <span style="FONT-WEIGHT: normal">public class StreamTool {
  2. /**
  3. * 讀取輸入流數據
  4. * @param inStream
  5. * @return
  6. */
  7. public static byte[] read(InputStream inStream) throws Exception{
  8. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  9. byte[] buffer = new byte[1024];
  10. int len = 0;
  11. while( (len = inStream.read(buffer)) != -1 ){
  12. outStream.write(buffer, 0, len);
  13. }
  14. inStream.close();
  15. return outStream.toByteArray();
  16. }
  17. }
Copyright © Linux教程網 All Rights Reserved