使用日历设置警报通知android

时间:2015-06-05 01:20:51

标签: android notifications android-alarms

我正在尝试根据用户输入的日期和时间弹出通知。这是我获取时间值的代码

        // String GetRawDate Gets The User Value For Date//
        String getRawDate = date.getText().toString();

        // String SplitDate Splits The Date Into Three Separate Ints//
        String[] splitDate = getRawDate.split("/");

        // Int GetMonth Gets The Value Of The Month//
        int getMonth = Integer.parseInt(splitDate[0]);

        // Int GetDay Gets The Value Of The Day//
        int getDay = Integer.parseInt(splitDate[1]);

        // Int GetYear Gets The Value Of The Year//
        int getYear = Integer.parseInt(splitDate[2]);

        // Get Military Start Time//
        String test = military_start_time;

        // Split It//
        String[] splitStartTime = test.split(":");

        // Get Hour In Integer Form
        int getHour = Integer.parseInt(splitStartTime[0]);

        // Get Minute In Integer Form//
        int getMinute = Integer.parseInt(splitStartTime[1]);

从这里我将这些值添加到日历

        // Gets Calendar Instance//
        Calendar calendar =  Calendar.getInstance();

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, getMonth);
        cal.set(Calendar.YEAR, getYear);
        cal.set(Calendar.DAY_OF_MONTH, getDay);
        cal.set(Calendar.HOUR_OF_DAY, getHour);
        cal.set(Calendar.MINUTE, getMinute);

然后我设置闹钟

        // Intent To Start Notification After X Seconds//
        Intent alertIntent = new Intent(this, ReminderService.class);
        alertIntent.putExtra("name", name.getText().toString());
        alertIntent.putExtra("time", starttime.getText().toString());

        // Defines Alarm Manager//
        AlarmManager alarmManager = (AlarmManager)   
        getSystemService(Context.ALARM_SERVICE);

        // Sets Alarm Manager//
        alarmManager.set(AlarmManager.RTC_WAKEUP, 
        calendar.getTimeInMillis(), PendingIntent.getBroadcast(this, 1, 
        alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));

        // Starts Activity ListView//
        Intent b = new Intent(this, Reminders.class);
        startActivity(b);
        overridePendingTransition(R.anim.slid_in, R.anim.slid_out);

假设用户的日期为6/4/15,时间为22:10,我希望此时显示通知。出于某种原因,它会在代码运行后显示约5秒钟。有谁知道我在报警时做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试使用

    alarmManager.setExact(AlarmManager.RTC_WAKEUP, 
    cal.getTimeInMillis(), PendingIntent.getBroadcast(this, 1, 
    alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));

P.S:需要最低API:19