画像を非同期でダウンロードする|Android開発

WebAPIからJSON形式のデータを取得する|Android開発
上記の記事では文字列(JSON)の取得でしたが、今回は非同期で画像をダウンロードする処理になります。取得結果をBitmapクラスにするのと、タイムアウト時間を調整する以外、やることは同じです。

AsyncTask を使って画像ファイルをダウンロードする

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

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

public class GetHttpImageAsyncTask extends AsyncTask<URL, Void, Bitmap> {
    private static final String TAG = "GetHttpImageAsyncTask";

    public interface ResponseListener {
        void onReceived(Bitmap responseData);
    }

    private ResponseListener mListener;

    public GetHttpImageAsyncTask(ResponseListener listener) {
        if (listener == null) {
            listener = new ResponseListener() {
                @Override
                public void onReceived(Bitmap responseData) {
                }
            };
        }
        mListener = listener;
    }

    @Override
    protected Bitmap doInBackground(URL... urls) {

        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) urls[0].openConnection();
            connection.setRequestMethod("GET");
            connection.addRequestProperty("User-agent", "Android");
            connection.addRequestProperty("Accept-Language", Locale.getDefault().toString());
            // リダイレクトなし.
            connection.setInstanceFollowRedirects(false);
            // データ入力用.
            connection.setDoInput(true);
            connection.setDoOutput(false);
            // 接続タイムアウト. 20sec.
            connection.setConnectTimeout(20000);
            // 読み取りタイムアウト. 60sec.
            connection.setReadTimeout(60000);
            connection.connect();

            InputStream iStream = null;
            Bitmap bitmap = null;
            try {
                iStream = connection.getInputStream();
                bitmap = BitmapFactory.decodeStream(iStream);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                closeInputStream(iStream);
            }

            return bitmap;

        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "HttpURLConnection method is error.");
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    @Override
    protected void onPostExecute(Bitmap bmp) {
        mListener.onReceived(bmp);
    }

    private static void closeInputStream(InputStream stream) {
        if (stream == null) {
            return;
        }
        try {
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

呼び出し側

private boolean requestImage(String imageUrl) {
    try {
        URL url = new URL("画像ファイルのURL");
        GetHttpImageAsyncTask httpTask = new GetHttpImageAsyncTask(mRequestImageListener);
        httpTask.execute(url);
        return true;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return false;
    }
}

private GetHttpImageAsyncTask.ResponseListener mRequestImageListener = new GetHttpImageAsyncTask.ResponseListener() {
    @Override
    public void onReceived(Bitmap responseData) {
        findViewById(R.id.wait_details_progress).setVisibility(View.INVISIBLE);

        if (responseData == null) {
            // 取得失敗時の処理. (エラー画像設定など)
            return;
        }

        // 取得成功時の処理. (画面への画像表示など)
    }
};
このエントリーをはてなブックマークに追加
にほんブログ村 IT技術ブログへ

スポンサードリンク

関連コンテンツ

コメント

メールアドレスが公開されることはありません。 が付いている欄は必須項目です