显示特定日期和时间的通知

时间:2015-06-27 07:17:22

标签: android broadcastreceiver alarmmanager

我需要在特定日期和时间(27-06-2015 13:00)显示通知。最初我正在展示祝酒词。我已经创建了一个广播接收器来做到这一点。我正在调用这样的未决意图 -

活动代码 -

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

我试图通过更改手机的时间来检查。我正在将手机时间更改为12:59。但是当我呼叫广播接收器时,它立即发出吐司消息,它应该按照我的逻辑时间13:00显示。我做错了吗?

1 个答案:

答案 0 :(得分:2)

在您的代码中看起来很清楚,可能是您初始化Calendar obj的问题。

尝试如下,

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

并设置

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

希望这会对你有所帮助。