【发布时间】:2011-09-02 18:37:02
【问题描述】:
我已实现 AlarmManager 每天唤醒手机一次以执行更新任务、更新小部件并在适用时发送通知。
我正在使用 setRepeating 和 ELAPSED_REALTIME_WAKEUP
第一时间触发报警(SystemClock.elapsedRealtime()+60000)
但它不会在 86400000 毫秒(24 小时)后触发。
真的在为此苦苦挣扎,我很高兴接受我做错了什么,或者如果有更好的方法来实现我想要做的事情。但是我认为我的代码看起来像是人们似乎在做的标准事情。
这几乎就像重复警报在所有情况下都没有按照它所说的那样做。如果我将时间间隔缩短到 10 分钟,它确实有效,我的警报就会触发,并且服务会一遍又一遍地运行。
我的应用程序的性质意味着每天更新一次以上是多余的。 我需要为此找到一个现实可靠的解决方案。
感谢您的宝贵时间,希望您能指出正确的方向。
这是我的闹钟实现代码...
清单:
<receiver android:name=".SystemChangeReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE" />
</intent-filter>
</receiver>
<receiver android:name=".UpdateAlarmReceiver" />
<service android:name=".UpdateService" />
<receiver android:name=".WidgetProviderSmall" android:label="@string/widget_small_label">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidget_small" />
</receiver>
<receiver android:name=".WidgetProviderLarge" android:label="@string/widget_large_label">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidget_large" />
</receiver>
SystemChangeReceiver 监听开机广播,检查是否需要设置警报,如果需要,则设置。
SystemChangeReceiver:
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences prefs = context.getSharedPreferences(context.getString(R.string.prefs_name), 0);
Boolean notifications = prefs.getBoolean("enable_updates", false);
if(notifications == true) {
Utils.setNotificationAlarm(context);
}
}
setNotificationAlarm 方法,设置重复报警...
public static void setNotificationAlarm(Context context) {
AlarmManager alarmManager=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, UpdateAlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.setRepeating(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime()+60000,
86400000,
pi);
}
当警报触发我的接收器UpdateAlarmReceiver 决定做什么并使用WakefulIntentService 运行我的后台更新过程时,服务的处理程序然后更新小部件并根据需要发送通知
UpdateAlarmReceiver:
public void onReceive(Context context, Intent intent) {
WakefulIntentService.sendWakefulWork(context, UpdateService.class);
}
【问题讨论】:
-
可以解决所有这些问题的快速问题:您使用任务杀手吗?您的应用是否在其白名单中?
-
我实际上正在使用 AutoKiller Memory Optimizer 它没有白名单这可能是问题吗?根据进程列表,我的应用仍在运行。
标签: android alarmmanager