多次接收报警意图



我需要每天上午 11 点触发一次闹钟,并更新我的所有小部件。当我使用一个小部件测试我的应用程序时,我的 onReceive(( 方法会在时间到来后多次触发,每次都会更新我的小部件。为什么会这样?

这是我的代码:

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
theAppWidgetManager = appWidgetManager;
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
...
}
scheduleNextUpdate(context);
}
@Override
public void onReceive(Context context, Intent intent){
if (intent.getAction().equals(ACTION_SCHEDULED_UPDATE)) {
AppWidgetManager manager = AppWidgetManager.getInstance(context);
int[] ids = manager.getAppWidgetIds(new ComponentName(context, AppWidget.class));
onUpdate(context, manager, ids);
}
super.onReceive(context, intent);
}
private  void scheduleNextUpdate(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AppWidget.class);
intent.setAction(ACTION_SCHEDULED_UPDATE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
// Get a calendar instance for midnight tomorrow.
Calendar at11 = Calendar.getInstance();
at11.set(Calendar.HOUR_OF_DAY, 11);
at11.set(Calendar.MINUTE, 30);
at11.set(Calendar.SECOND, 1);
at11.set(Calendar.MILLISECOND, 0);
at11.add(Calendar.DAY_OF_YEAR, 1);
// For API 19 and later, set may fire the intent a little later to save battery,
// setExact ensures the intent goes off exactly at midnight.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
alarmManager.set(AlarmManager.RTC_WAKEUP, at11.getTimeInMillis(), pendingIntent);
} else {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, at11.getTimeInMillis(), pendingIntent);
}
}

我认为这里的问题是您正在onUpdate方法中安排下一次更新。这种方法的描述说:

响应AppWidgetManager.ACTION_APPWIDGET_UPDATE和 AppWidgetManager.ACTION_APPWIDGET_RESTORED在此情况下广播 AppWidget 提供程序被要求为一组 应用小部件。

因此,理论上它可以触发多次。我认为您应该在onReceive安排下一次更新,或者以某种方式检查下一次更新的广播是否已安排

相关内容

  • 没有找到相关文章

最新更新