AsyncTask应用,获取在线网络图标Bitmap数据

73 阅读1分钟

本文是对AsynckTask的应用,在获取网络数据中一般需要在主线程中另开一个子线程来进行网络数据的获取,但是会出现获取数据不同步的问题,使用AsyncTask可以简单的解决这一问题。下面以获取网络图标的bitmap数据为例。

  1. 创建AsyncTask
//通过AsyncTask获取图标

//创建获取AsyncTask返回的bitmap数据接口
public interface AsyncResponse {
    void onDataReceivedSuccess(Bitmap bitmap);
    void onDataReceivedFailed();
}

private class DownloadAsyncTask extends AsyncTask<String, Void, Bitmap> {

    public AsyncResponse asyncResponse;
    public void setOnAsyncResponse(AsyncResponse asyncResponse) {
        this.asyncResponse = asyncResponse;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
        if (bitmap != null) {
            asyncResponse.onDataReceivedSuccess(bitmap);//将结果传给回调接口中的函数
        } else {
            asyncResponse.onDataReceivedFailed();
        }
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        Bitmap bitmap = null;
        try {
            URL iconUrl = new URL(params[0]);
            URLConnection conn = iconUrl.openConnection();
            HttpURLConnection http = (HttpURLConnection) conn;
            int length = http.getContentLength();
            conn.connect();
            // 获得图像的字符流
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, length);
            bitmap = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();// 关闭流
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

}

2.通过自定义的返回接口获取数据

DownloadAsyncTask test = new DownloadAsyncTask();
test.execute(url);
test.setOnAsyncResponse(new AsyncResponse() {
    @Override
    public void onDataReceivedSuccess(Bitmap bitmap){
    //从这里取得bitmap
    Bitmap bm = bitmap;
    }
    @Override
    public void onDataReceivedFailed() {
    }
});