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:
//....publicclassDownloadBitmapextendsAsyncTask<String, Void, Bitmap> {
    private RemoteViews views;
    publicDownloadBitmap(RemoteViews views){
        this.views = views;
    }
    //.....publicvoidonPostExecute(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:
publicclassDownloadBitmapextendsAsyncTask<String, Void, Bitmap> {
    /** The url from where to download the image. */privateStringurl="http://0.tqn.com/d/webclipart/1/0/5/l/4/floral-icon-5.jpg"; 
    private RemoteViews views;
    privateint WidgetID;
    private AppWidgetManager WidgetManager;
    publicDownloadBitmap(RemoteViews views, int appWidgetID, AppWidgetManager appWidgetManager){
        this.views = views;
        this.WidgetID = appWidgetID;
        this.WidgetManager = appWidgetManager;        
    }
@Overrideprotected Bitmap doInBackground(String... params) {
    try {
        InputStreamin=newjava.net.URL(url).openStream();
        Bitmapbitmap= 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());
    }
    returnnull;
}
@OverrideprotectedvoidonPostExecute(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"