*由于在开发的过程中用异步任务下载的东西一般是json和图片
*所以本工具类只涉及到这两种类型,如果有兴趣,再或者有其他的需求的话,自己可以扩充工具类的功能
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.security.auth.PrivateCredentialPermission;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
public class PottingAsyncTask extends AsyncTask<String, Void, Object> {
private OnDownLitener onDownLitener;
private DownType downType;
public PottingAsyncTask(DownType downType) {
// TODO Auto-generated constructor stub
this.downType = downType;
}
//子线程
@Override
protected Object doInBackground(String... arg0) {
// TODO Auto-generated method stub
byte[] bs = getByteArray(arg0[0]);
if (bs != null) {
switch (downType) {
case JSON:
String json = new String(bs);
if(onDownLitener!=null){
Object datasObject=onDownLitener.downJson(json);
return datasObject;
}
break;
case IMAGE:
Bitmap bitmap = BitmapFactory.decodeByteArray(bs, 0, bs.length);
return bitmap;
default:
break;
}
}
return null;
}
//在执行完doInBackground后再执行onPostExecute
@Override
protected void onPostExecute(Object result) {
switch (downType) {
case JSON:
if(onDownLitener!=null){
onDownLitener.paresJson(result);
}
break;
case IMAGE:
if(onDownLitener!=null){
onDownLitener.setImage(result);
}
break;
default:
break;
}
}
//构建接口,使用接口回调的方式控制控件
public interface OnDownLitener{
Object downJson(String json);
void paresJson(Object object);
void setImage(Object object);
}
//获得byte数组
private byte[] getByteArray(String urlString) {
InputStream in = null;
ByteArrayOutputStream ou = null;
URL url;
try {
url = new URL(urlString);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(3000);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
in = httpURLConnection.getInputStream();
ou=new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 8];
int len = -1;
while ((len = in.read(buffer)) != -1) {
ou.write(buffer, 0, len);
}
return ou.toByteArray();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (ou != null) {
try {
ou.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
//借助泛型,确定所需要的类型
public static enum DownType {
JSON, IMAGE
}
//接口回调的方法
public PottingAsyncTask setOnDownLitener(OnDownLitener onDownLitener) {
this.onDownLitener = onDownLitener;
return this;//返回this的原因是链式编程,返回当前PottingAsyncTask的对象
}
}