如何使用Asynctask替换以下代码行?如何从Asynctask中“获取”位图?谢谢。
ImageView mChart = (ImageView) findViewById(R.id.Chart);
String URL = "http://www...anything ...";
mChart.setImageBitmap(download_Image(URL));
public static Bitmap download_Image(String url) {
//---------------------------------------------------
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//---------------------------------------------------
}
我考虑了这样的方案:替换:
mChart.setImageBitmap(download_Image(graph_URL));
通过类似于以下方式:
mChart.setImageBitmap(new DownloadImagesTask().execute(graph_URL));
并且public class DownloadImagesTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... urls) {
return download_Image(urls[0]);
}
@Override
protected void onPostExecute(Bitmap result) {
mChart.setImageBitmap(result); // how do I pass a reference to mChart here ?
}
private Bitmap download_Image(String url) {
//---------------------------------------------------
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//---------------------------------------------------
}
}
但是,我如何在onPostExecute(Bitmap result)中传递对mChart的引用?是否需要以某种方式将其与URL一起传递?我想替换掉所有代码行:
但如何在onPostExecute(Bitmap result)中传递对mChart的引用?是否需要通过URL以某种方式进行传递?我希望替换掉我的所有代码行:
mChart1.setImageBitmap(download_Image(URL_1));
mChart2.setImageBitmap(download_Image(URL_2));
使用类似的方法...但采用异步任务方式!
mChart1.setImageBitmap(new DownloadImagesTask().execute(graph_URL_1));
mChart2.setImageBitmap(new DownloadImagesTask().execute(graph_URL_2));
有没有简单的解决方案? 我这里做错了什么吗?