Android 启动时发送通知

Android notification sent on start

我已经设置了一个闹钟管理器,每天中午关闭并发送通知,除了一个部分外,它工作正常。当我第一次打开应用程序时,它会立即发出通知,而不管时间。

Intent myIntent = new Intent(arg0, NotificationService.class);
    myIntent.putExtra("compDate", tti.getEvents()[0][1]);
    AlarmManager alarmManager = (AlarmManager)arg0.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getService(arg0, 0, myIntent, 0);

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.HOUR, 12);
    calendar.set(Calendar.AM_PM, Calendar.AM);
    calendar.set(Calendar.DAY_OF_MONTH, 1);

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

onCreate 方法中的这段代码正在调用该方法

int f = preferences.getInt("numberOfLaunches", 1);

    if(f < 2){
        alarmMethod();
        f++;
        editor.putInt("numberOfLaunches", f);
        editor.apply();
    }

那是唯一一次被调用

最可能的原因是:

If the stated trigger time is in the past, the alarm will be triggered immediately

http://developer.android.com/reference/android/app/AlarmManager.html#setRepeating

确保将第一个闹钟设置在未来。

好的,多亏了这个问题:Android alarm sets off immediately 和 Kuffs 的回答,我添加了这段代码,效果非常好。

Date dat  = new Date();
    Calendar cal_alarm = Calendar.getInstance();
    Calendar cal_now = Calendar.getInstance();
    cal_now.setTime(dat);
    cal_alarm.setTime(dat);
    cal_alarm.set(Calendar.HOUR_OF_DAY, 12);
    cal_alarm.set(Calendar.MINUTE, 0);
    cal_alarm.set(Calendar.SECOND, 0);

    if(cal_alarm.before(cal_now)){
        cal_alarm.add(Calendar.DATE,1);
    }