启动时发送Android通知

时间:2015-12-04 12:05:56

标签: android notifications alarm

我已经设置了一个警报管理员,每天中午出发并发送通知,并且除了一部分外,工作正常。当我第一次打开应用程序时,无论何时,它都会立即发出通知。

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();
    }

这是唯一被称为

的时间

2 个答案:

答案 0 :(得分:0)

最有可能是由此造成的:

  

如果声明的触发时间是过去的,则会立即触发警报

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

确保将您的第一个闹钟设置为将来。

答案 1 :(得分:0)

好的,感谢这个问题: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);
    }