廣告

2014年11月30日 星期日

[Android 顯示從網路下載的圖片][Android show picture from url]

常常會用到即時從網路下載圖片,並顯示於原件上。
下載圖片的方式有很多種,這邊用AsyncTask 搭配 http GET的方式顯示
圖片在imageView上,(可以自行將imageView 改成其他元件,grid, list等等)。










































範例:


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

public class Lewis extends Activity {
 private ImageView imageView;
 private ProgressDialog simpleWaitDialog;
 private final static String url = "http://i.imgur.com/pJv6ccq.jpg";

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  imageView = (ImageView) findViewById(R.id.imageView);
  new DownloadImage().execute(url); 
 }

 private class DownloadImage extends AsyncTask {
  @Override
  protected Bitmap doInBackground(String... param) {
   return downloadBitmap(param[0]);
  }

  @Override
  protected void onPreExecute() {
   simpleWaitDialog = ProgressDialog.show(
     Lewis.this, "Wait",
     "Downloading Image");
  }

  protected void onPostExecute(Bitmap result) {
   imageView.setImageBitmap(result);
   simpleWaitDialog.dismiss();

  }

  private Bitmap downloadBitmap(String url) {
   final DefaultHttpClient client = new DefaultHttpClient();
   final HttpGet getRequest = new HttpGet(url);
   try {
    HttpResponse response = client.execute(getRequest);
    final int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
     return null;
    }
    final HttpEntity entity = response.getEntity();
    if (entity != null) {
     InputStream inputStream = null;
     try {
      inputStream = entity.getContent();
      final Bitmap bitmap = BitmapFactory
        .decodeStream(inputStream);
      
      return bitmap;
      
     } finally {
      if (inputStream != null) {
       inputStream.close();
      }
      entity.consumeContent();
     }
    }
   } catch (Exception e) {

    getRequest.abort();
   }
   return null;
  }
 }
}

2 則留言:

  1. 作者已經移除這則留言。

    回覆刪除
  2. 請坂大修正一下第42行

    AsyncTask

    這邊應該是排版時格式跑掉吧?

    回覆刪除