使用来自互联网的图像更新android小部件(使用异步任务)

使用来自互联网的图像更新android小部件(使用异步任务),第1张

概述我有一个简单的 Android小部件,我想用互联网上的图像更新.我可以在小部件上显示静态图像没问题.我被告知你需要使用异步任务,我对这些没有多少经验. 这是我的小部件: @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetI 我有一个简单的 Android小部件,我想用互联网上的图像更新.我可以在小部件上显示静态图像没问题.我被告知你需要使用异步任务,我对这些没有多少经验.

这是我的小部件:

@OverrIDe    public voID onUpdate(Context context,AppWidgetManager appWidgetManager,int[] appWidgetIDs) {        super.onUpdate(context,appWidgetManager,appWidgetIDs);        for (int i = 0; i < appWidgetIDs.length; i++){            int appWidgetID = appWidgetIDs[i];                  RemoteVIEws vIEws = new RemoteVIEws(context.getPackagename(),R.layout.activity_main);                //Setup a static image,this works fine.            vIEws.setimageVIEwResource(R.ID.imageVIEw1,R.drawable.wordpress_icon);                         new DownloadBitmap().execute("MyTestString");                   appWidgetManager.updateAppWidget(appWidgetID,vIEws);        }

然后我有一个异步任务类来进行下载.它看起来像这样:

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";     @OverrIDe    protected Bitmap doInBackground(String... params) {        try {            inputStream in = new java.net.URL(url).openStream();            Bitmap bitmap = BitmapFactory.decodeStream(in);            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;        }           //Here is where I should set the image to the imagevIEw,but how?    } }

我认为我的代码已成功从互联网上下载图像.

我很困惑的是,如何从Async任务类中将此图像放入特定小部件的“ImageVIEw”中.要更新映像,您需要访问3个不同的对象:Context,AppWidgetManager和AppWidgetID ….但是如何在此语句中传递所有这些对象:???

new DownloadBitmap().execute("MyTestString");

谢谢!

解决方法 一种解决方案是将RemoteVIEws作为参数传递给DownloadBitmap构造函数,并在onPostExecute()中设置图像:

在onUpdate()中:

new DownloadBitmap(vIEws).execute("MyTestString");

并在DownloadBitmap中:

//....public class DownloadBitmap extends AsyncTask<String,Bitmap> {    private RemoteVIEws vIEws;    public DownloadBitmap(RemoteVIEws vIEws){        this.vIEws = vIEws;    }    //.....    public voID onPostExecute(Bitmap bitmap){        vIEws.setimageVIEwBitmap(R.ID.imageVIEw1,bitmap);    }}
总结

以上是内存溢出为你收集整理的使用来自互联网的图像更新android小部件(使用异步任务)全部内容,希望文章能够帮你解决使用来自互联网的图像更新android小部件(使用异步任务)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1138968.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-31
下一篇2022-05-31

发表评论

登录后才能评论

评论列表(0条)

    保存