如何用 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 一起传递?我想替换我所有的代码行:
mChart1.setImageBitmap(download_Image(URL_1));
mChart2.setImageBitmap(download_Image(URL_2));
有类似的东西......但在 Asynctask 方式!
mChart1.setImageBitmap(new DownloadImagesTask().execute(graph_URL_1));
mChart2.setImageBitmap(new DownloadImagesTask().execute(graph_URL_2));
有一个简单的解决方案吗?我在这里有什么问题吗?