package baway.com.imagloadasynctask.utils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 类的作用:
* 作者:岳俊飞
* 时间:2017/4/14
*/
* 类的作用:
* 作者:岳俊飞
* 时间:2017/4/14
*/
public class ImageLoadAsyncTask extends AsyncTask<String, Void, Bitmap> {
/**
* 定义一个图片的接口回调
*/
public interface ImageCallBack {
void callBitmap(Bitmap bitmap);
}
/**
* 定义一个图片的接口回调
*/
public interface ImageCallBack {
void callBitmap(Bitmap bitmap);
}
//定义变量记住调用者所传递进来的回调监听对象
private ImageCallBack imageCallBack;
private ImageCallBack imageCallBack;
//构造方法
public ImageLoadAsyncTask(ImageCallBack imageCallBack)
{
this.imageCallBack = imageCallBack;
}
public ImageLoadAsyncTask(ImageCallBack imageCallBack)
{
this.imageCallBack = imageCallBack;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap != null) {
//设置图片 回调回去
imageCallBack.callBitmap(bitmap);
}
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap != null) {
//设置图片 回调回去
imageCallBack.callBitmap(bitmap);
}
}
@Override
protected Bitmap doInBackground(String... params) {
try {
String path = params[0];
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
int code = connection.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {
//图片流
InputStream inputStream = connection.getInputStream();
//将图片流转化成Bitmap位图,返回
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
protected Bitmap doInBackground(String... params) {
try {
String path = params[0];
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
int code = connection.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {
//图片流
InputStream inputStream = connection.getInputStream();
//将图片流转化成Bitmap位图,返回
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}