我有一个简单的 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?
}
}
我认为我的代码已成功从互联网下载图像。
我感到困惑的是,如何将此图像从我的异步任务类获取到特定小部件的“ImageView”中。要更新图像,您需要访问 3 个不同的对象:Context、AppWidgetManager 和 AppWidgetId...但是我如何在该语句中传递所有这些对象:???
new DownloadBitmap().execute("MyTestString");
Thanks!