将 updatePeriodMillis 设置为 900000 毫秒是个好主意。这将每 15 分钟调用一次您的 onUpdate 方法。在 onUpdate 方法中,您可以“刷新”远程视图的待处理意图。您可以做的另一件事是在每次更改远程视图时执行小部件更新。例如,用户按下按钮执行您必须执行的操作,然后执行小部件更新。
有很多原因会导致挂起的意图被系统破坏,从而使您的远程视图失效,并且所有这些都很难找到和理解,因此最佳做法是每隔一段时间更新您的小部件。
我的研究表明,15 分钟是一个很好的时间框架。例如,这是我的 onUpdate 方法,它每 15 分钟运行一次,用于具有许多按钮的小部件:
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.d(TAG, "onUpdate");
super.onUpdate(context, appWidgetManager, appWidgetIds);
FullWidgetPreferencesHelper wp;
// If no specific widgets requested, collect list of all
if (appWidgetIds == null) {
appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, FullWidgetProvider.class));
}
for (int widgetId : appWidgetIds) {
Commands.FullWidgetUpdate(context, widgetId, 0); //<-- Update το widgetId
}
}
FullWidgetUpdate 方法是这样的:
...
views.setInt(R.id.cmdwifi, "setBackgroundResource", ThemeResources.getThemeResource(themeId, R.drawable.btn_bck_topleft_black));
views.setInt(R.id.cmdbluetooth, "setBackgroundResource", ThemeResources.getThemeResource(themeId, R.drawable.btn_bck_middle_black));
views.setInt(R.id.cmddata, "setBackgroundResource", ThemeResources.getThemeResource(themeId, R.drawable.btn_bck_middle_black));
views.setInt(R.id.cmdsync, "setBackgroundResource", ThemeResources.getThemeResource(themeId, R.drawable.btn_bck_middle_black));
views.setInt(R.id.cmdflight, "setBackgroundResource", ThemeResources.getThemeResource(themeId, R.drawable.btn_bck_middle_black));
views.setInt(R.id.cmdgps, "setBackgroundResource", ThemeResources.getThemeResource(themeId, R.drawable.btn_bck_middle_black));
views.setInt(R.id.cmdorientation, "setBackgroundResource", ThemeResources.getThemeResource(themeId, R.drawable.btn_bck_middle_black));
views.setInt(R.id.cmdvolume, "setBackgroundResource", ThemeResources.getThemeResource(themeId, R.drawable.btn_bck_topright_black));
...
final int PendingIntentFLAG = PendingIntent.FLAG_UPDATE_CURRENT;
Intent iWiFi = new Intent(cx, CommandsReceiver.class).setAction(CommandsReceiver.cmdwifi).setData(Uri.parse("custom:" + widgetID));
PendingIntent piWiFi = PendingIntent.getBroadcast(cx, 0, iWiFi, PendingIntentFLAG);
views.setOnClickPendingIntent(R.id.cmdwifi, piWiFi);
Intent iBT = new Intent(cx, CommandsReceiver.class).setAction(CommandsReceiver.cmdbt).setData(Uri.parse("custom:" + widgetID));
PendingIntent piBT = PendingIntent.getBroadcast(cx, 0, iBT, PendingIntentFLAG);
views.setOnClickPendingIntent(R.id.cmdbluetooth, piBT);
... and so on for other buttons ....
希望这可以帮助...