我有一个带小部件的Hijri日历应用程序。 Hijri日历的日期应使用AlarmManager在午夜更改。问题是尽管使用Alarm Manager来安排午夜更新,但小部件并不会在午夜12点准确更新。它会在12到凌晨1点之间更新。
我哪里错了?
爪哇:
private static PendingIntent service = null;
private static long UPDATES_CHECK_INTERVAL = 24 * 60 * 60 * 1000;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
schedule(context);
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
protected void schedule(Context context) {
final AlarmManager m = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
final Calendar TIME = Calendar.getInstance();
Date now = new Date();
TIME.add(Calendar.DAY_OF_MONTH, 1);
TIME.set(Calendar.HOUR_OF_DAY, 0);
TIME.set(Calendar.MINUTE, 0);
TIME.set(Calendar.SECOND, 0);
TIME.set(Calendar.MILLISECOND, 0);
long firstTime = (TIME.getTimeInMillis()-now.getTime());
final Intent i = new Intent(context, UpdateService.class);
if (service == null)
{
service = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
}
m.setRepeating(AlarmManager.RTC, firstTime, UPDATES_CHECK_INTERVAL, service);
}
清单:
<receiver android:name="com.example.app.Widget" android:label="Calendar" android:exported="false">
<intent-filter >
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="android.appwidget.action.APPWIDGET_ENABLED" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
<action android:name="android.intent.action.TIME_SET" />
<action android:name="android.intent.action.DATE_CHANGED" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget_info" />
</receiver>
答案 0 :(得分:4)
我认为您需要更改与Calender和AlarmManager相关的代码。
此日历表示第二天午夜的确切时间。并且AlarmManager将在那时每天激发意图。
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
calendar.add(Calendar.DAY_OF_MONTH, 1);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, service);
注意:我认为您应该在onEnabled()
方法中添加上述代码。 Here is a highlight of the AppWidgetProvider's related methods