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

前端之家收集整理的这篇文章主要介绍了使用来自互联网的图像更新android小部件(使用异步任务)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个简单的 Android小部件,我想用互联网上的图像更新.我可以在小部件上显示静态图像没问题.我被告知你需要使用异步任务,我对这些没有多少经验.

这是我的小部件:

  1. @Override
  2. public void onUpdate(Context context,AppWidgetManager appWidgetManager,int[] appWidgetIds) {
  3.  
  4. super.onUpdate(context,appWidgetManager,appWidgetIds);
  5.  
  6. for (int i = 0; i < appWidgetIds.length; i++){
  7. int appWidgetId = appWidgetIds[i];
  8.  
  9. RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.activity_main);
  10.  
  11. //Setup a static image,this works fine.
  12. views.setImageViewResource(R.id.imageView1,R.drawable.wordpress_icon);
  13.  
  14. new DownloadBitmap().execute("MyTestString");
  15.  
  16. appWidgetManager.updateAppWidget(appWidgetId,views);
  17. }

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

  1. public class DownloadBitmap extends AsyncTask<String,Void,Bitmap> {
  2.  
  3. /** The url from where to download the image. */
  4. private String url = "http://0.tqn.com/d/webclipart/1/0/5/l/4/floral-icon-5.jpg";
  5.  
  6. @Override
  7. protected Bitmap doInBackground(String... params) {
  8. try {
  9. InputStream in = new java.net.URL(url).openStream();
  10. Bitmap bitmap = BitmapFactory.decodeStream(in);
  11. return bitmap;
  12. //NOTE: it is not thread-safe to set the ImageView from inside this method. It must be done in onPostExecute()
  13. } catch (Exception e) {
  14. Log.e("ImageDownload","Download Failed: " + e.getMessage());
  15. }
  16. return null;
  17. }
  18.  
  19.  
  20. @Override
  21. protected void onPostExecute(Bitmap bitmap) {
  22. if (isCancelled()) {
  23. bitmap = null;
  24. }
  25.  
  26. //Here is where I should set the image to the imageview,but how?
  27. }
  28. }

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

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

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

谢谢!

解决方法

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

在onUpdate()中:

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

并在DownloadBitmap中:

  1. //....
  2. public class DownloadBitmap extends AsyncTask<String,Bitmap> {
  3. private RemoteViews views;
  4.  
  5. public DownloadBitmap(RemoteViews views){
  6. this.views = views;
  7. }
  8.  
  9. //.....
  10. public void onPostExecute(Bitmap bitmap){
  11. views.setImageViewBitmap(R.id.imageView1,bitmap);
  12. }
  13. }

猜你在找的Android相关文章