Update Android Widget (using Async Task) With An Image From The Internet
I have a simple android widget that I want to update with an image from the internet. I can display static images on the widget no problem. I am told that you need to use an asyn
Solution 1:
One solution would be to pass the RemoteViews
as an argument to the DownloadBitmap
constructor, and in onPostExecute()
to set the image:
In onUpdate():
new DownloadBitmap(views).execute("MyTestString");
and in the DownloadBitmap:
//....
public class DownloadBitmap extends AsyncTask<String, Void, Bitmap> {
private RemoteViews views;
public DownloadBitmap(RemoteViews views){
this.views = views;
}
//.....
public void onPostExecute(Bitmap bitmap){
views.setImageViewBitmap(R.id.imageView1, bitmap);
}
}
Solution 2:
Please see Andy Res's solution above. I tweaked it ever so slightly to pass more parameters... but it works!!!!
I call it like this:
new DownloadBitmap(views, appWidgetId, appWidgetManager).execute("MyTestString");
then, my task starts like this:
public class DownloadBitmap extends AsyncTask<String, Void, Bitmap> {
/** The url from where to download the image. */
private String url = "http://0.tqn.com/d/webclipart/1/0/5/l/4/floral-icon-5.jpg";
private RemoteViews views;
private int WidgetID;
private AppWidgetManager WidgetManager;
public DownloadBitmap(RemoteViews views, int appWidgetID, AppWidgetManager appWidgetManager){
this.views = views;
this.WidgetID = appWidgetID;
this.WidgetManager = appWidgetManager;
}
@Override
protected Bitmap doInBackground(String... params) {
try {
InputStream in = new java.net.URL(url).openStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
Log.v("ImageDownload", "download succeeded");
Log.v("ImageDownload", "Param 0 is: " + params[0]);
return bitmap;
//NOTE: it is not thread-safe to set the ImageView from inside this method. It must be done in onPostExecute()
} catch (Exception e) {
Log.e("ImageDownload", "Download failed: " + e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
views.setImageViewBitmap(R.id.imageView1, bitmap);
WidgetManager.updateAppWidget(WidgetID, views);
}
Post a Comment for "Update Android Widget (using Async Task) With An Image From The Internet"