show a notification on a particular date and time

2019-02-19 11:58发布

问题:

I need to show a notification on a particular date and time (27-06-2015 13:00). Initially I am showing a toast message. I have created a broadcast receiver to do that. I am calling the pending intent like this -

Activity Code -

Calendar cal=Calendar.getInstance();
cal.set(Calendar.MONTH,(5));
cal.set(Calendar.YEAR,2015);
cal.set(Calendar.DAY_OF_MONTH, 27);
cal.set(Calendar.HOUR_OF_DAY,13);
cal.set(Calendar.MINUTE,00);

Intent myIntent1 = new Intent(this, AlarmBroadCustReciver.class);
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this, 1253, myIntent1,
        PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager1.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent1);

Broadcust Receiver Code -

public class AlarmBroadCustReciver extends BroadcastReceiver {
    public AlarmBroadCustReciver() {
    }

    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
    }
}

I am trying to check that by changing the time of my phone.I am changing the phone time to 12:59. But When I am calling the Broadcast Receiver it instantly giving the toast message it should show when the time is 13:00 as per my logic. Am I doing anything wrong?

回答1:

Every thing looks clear in your code may be it is the problem of Calendar obj that you have initialized.

Once try as follows,

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.clear();
cal.set(2015,5,27,13,00); 

And to set

alarmManager1.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent1);

Hope this will helps you.