Skip to content

Instantly share code, notes, and snippets.

@edwardinubuntu
Created June 27, 2017 05:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edwardinubuntu/8418155e926c35882d75b51d45dbaabe to your computer and use it in GitHub Desktop.
Save edwardinubuntu/8418155e926c35882d75b51d45dbaabe to your computer and use it in GitHub Desktop.
Download image with OKHttpClient in AsyncTask.
package io.triptime.android.service;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import java.io.IOException;
import io.triptime.android.TripTime;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by edward_chiang on 27/06/2017.
*/
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
private OnBitmapDownloadListener onBitmapDownloadListener;
@Override
protected Bitmap doInBackground(String... strings) {
final OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(strings[0])
.build();
Response response = null;
Bitmap mIcon11 = null;
try {
response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
if (response.isSuccessful()) {
try {
mIcon11 = BitmapFactory.decodeStream(response.body().byteStream());
} catch (Exception e) {
Log.e(TripTime.TAG, e.getMessage());
e.printStackTrace();
}
}
return mIcon11;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (onBitmapDownloadListener != null) {
onBitmapDownloadListener.result(bitmap);
}
}
public OnBitmapDownloadListener getOnBitmapDownloadListener() {
return onBitmapDownloadListener;
}
public void setOnBitmapDownloadListener(OnBitmapDownloadListener onBitmapDownloadListener) {
this.onBitmapDownloadListener = onBitmapDownloadListener;
}
public interface OnBitmapDownloadListener {
public void result(Bitmap bitmap);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment