警报通知未出现

时间:2017-08-08 02:12:51

标签: java android alarmmanager android-notifications

我在收到每日通知时遇到了一些麻烦。

我的应用程序获得用户希望被提醒某事的时间,一小时和一分钟。

然后我使用AlarmManager设置闹钟,此时重复使用闹钟接收器创建通知。

我已经尝试了几个小时,但无法弄清楚我做错了什么。

我看过其他一些SO问题,但没有人帮助过我。

我已将用户的小时和分钟输入存储到日期对象get habitReminder中。

我的createNotifications()方法:

private void createNotifications() {
    Log.i("Reminder at",""+habitReminder.getHours()+":"+habitReminder.getMinutes());
    //Create the alarms/notifications for the user
    Intent alarmIntent = new Intent(this, AlarmReceiver.class);
    alarmIntent.putExtra("name", habitName);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);

    Log.i("createNotifications", "Alarm manager is created.");

    //Set the timing of the reminder
    Calendar calendar = Calendar.getInstance();
    Calendar now = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, habitReminder.getHours());
    calendar.set(Calendar.MINUTE, habitReminder.getMinutes());
    calendar.set(Calendar.SECOND,0);

    //Check to make sure time is after the current date.
    if(calendar.before(now)){
        calendar.add(Calendar.DATE, 1);
    }

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

    Log.i("createNotifications", "Alarm has been set for " +habitReminder.getHours()+":"+habitReminder.getMinutes() +" daily.");
}

我的闹钟接收器类:

public class AlarmReceiver extends BroadcastReceiver {

private static int id =0;

@Override
public void onReceive(Context context, Intent intent) {
    String name = intent.getStringExtra("name");
    String title = name + " Reminder!";
    String message = "Your reminder to keep up your habit!";
    long when = System.currentTimeMillis();
    Intent in = new Intent(context, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context,0,in,PendingIntent.FLAG_CANCEL_CURRENT);
    NotificationManager nM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification.Builder builder = new Notification.Builder(context)
            .setContentIntent(contentIntent)
            .setContentTitle(title)
            .setContentText(message)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setAutoCancel(true)
            .setWhen(when);
    Notification notification = builder.build();
    nM.notify(id,notification);
    id++;
}

}

我的机器人manifest

<receiver android:name="com.closedbracket.trackit.AlarmReceiver" android:enabled="true">
</receiver>

真的很感激任何帮助。

2 个答案:

答案 0 :(得分:1)

如果您想要精确可靠的警报,请使用setAlarmClock。它会从电池消耗更多电量,但您确定警报会在设定的时间内精确响铃。

有关详细信息,请参阅Difference between setExact and setAlarmClock

答案 1 :(得分:0)

我认为你有setRepeating错误的论点。第二个参数是第一个警报触发之前的时间间隔(抖动)。第三个是在第一次出现后续警报触发的间隔(间隔)。

您正在设置AlarmManager.INTERVAL_DAY的警报,其值为86400000.您的警报每天会触发一次。