每天使用 AlarmManager 和 Service 显示通知

Display notification daily with AlarmManager and Service

我想每天显示一个通知,但是通知每隔一段时间显示一次。到目前为止我还没有弄清楚这个模式。

在我的 MainActivity#onCreate 中,我执行以下代码来启动它:

final Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.add(Calendar.DAY_OF_YEAR, 1);

final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, getPendingIntentForDailyReminderService(context));

为了停止 AlarmManager,我有这段代码(它仅在用户更改首选项时执行):

final AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
alarmManager.cancel(getPendingIntentForDailyReminderService(context));

函数getPendingIntentForDailyReminderService定义如下:

final Intent intent = new Intent(context, DailyReminderService.class);
return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

这是我的服务class:

public class DailyReminderService extends Service {
    private static final int NOTIFICATION_ID = 1;

    @Override
    public IBinder onBind(final Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(final Intent intent, final int flags, final int startId) {
        final String contentText = this.getString(R.string.daily_reminder_text);

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle(this.getString(R.string.app_name));
        builder.setContentText(contentText);
        builder.setSmallIcon(R.drawable.ic_notification_icon);
        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(contentText));

        final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);

        final Notification notification = builder.build();
        notification.flags = Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;

        final NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, notification);

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        final NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancel(NOTIFICATION_ID);

        super.onDestroy();
    }
}

我还在清单中注册了该服务:

<service
    android:name=".dailyreminder.DailyReminderService"
    android:enabled="true"
    android:exported="true">

我做错了什么?

正确的方法是使用 BroadcastReceiver 而不是 Service

如果您从 onStartCommand return START_STICKY 并且从未明确停止服务,每次服务因资源不足而被终止时, OS 将尝试稍后在有资源时重新启动服务。