【发布时间】:2010-07-26 00:35:48
【问题描述】:
我决定在这个周末创建我的第一个 Android 小部件,虽然我已经让它工作了一些,但它不会显示动态加载的内容,直到我旋转设备(使用 Launcher Pro Plus,它允许横向和家庭旋转屏幕)。
这个小部件非常简单,它只是从网站检索图像并显示图像。我创建了一个在 AppWidgetProvider 子类的 onUpdate() 中启动的服务。该服务然后检索图像,构建 RemoteViews 对象,然后调用 AppWidgetManager 上的 updateAppWidget()。这是小部件的代码:
public class PropagationWidget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
context.startService(new Intent(context, UpdateService.class));
}
public static class UpdateService extends IntentService {
public UpdateService() {
super("PropagationWidget$UpdateService");
}
@Override
protected void onHandleIntent(Intent intent) {
ComponentName me=new ComponentName(this,
PropagationWidget.class);
AppWidgetManager mgr=AppWidgetManager.getInstance(this);
mgr.updateAppWidget(me, buildUpdate(this));
}
public RemoteViews buildUpdate(Context context) {
RemoteViews views = null;
URL imageUrl = null;
try {
views = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
imageUrl = new URL(
"http://www.mountainlake.k12.mn.us/ham/aprs/path.cgi?map=na&img=node&freq=144&type=image");
InputStream is = (InputStream) imageUrl.getContent();
Bitmap image = BitmapFactory.decodeStream(is);
views.setImageViewBitmap(R.id.image, image);
Time today = new Time();
today.setToNow();
views.setTextViewText(R.id.last_updated, "Last updated: " + today.format("%D %r"));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return views;
}
}
当小部件加载时,我只得到小部件的框架,但没有内容,这是有道理的,因为 UpdateService 还没有从网站上检索到图像。但是,即使在 UpdateService 完成检索图像并立即调用 updateAppWidget() 之后,图像仍然不会出现。但是,当我旋转设备时,图像会出现,并且会在后续旋转时保留。
此外,小部件在 appwidget-provider XML 中设置为每 30 分钟更新一次。这些更新在我旋转设备之前不会显示,当重新绘制小部件时,我会看到更新。
这里有什么我缺少的真正基本的东西吗?任何见解将不胜感激!如果我应该提供任何其他信息来帮助解决这个问题,请告诉我。
【问题讨论】: