Notification at Specific Time using BroadcastReceiver and AlarmManager

后端 未结 3 1243
臣服心动
臣服心动 2021-01-03 17:13

I want to send notification at specific time using broadcast receiver. many tutorials videos and also answers has been read in this regard and all of them was clear. but I c

3条回答
  •  暖寄归人
    2021-01-03 17:44

    If you wish to have a timer expire at an exact time, then you can configure the timer as follows.

    Calendar alarmFor = Calendar.getInstance();
    alarmFor.set(Calendar.HOUR_OF_DAY, 7);
    alarmFor.set(Calendar.MINUTE, 45);
    alarmFor.set(Calendar.SECOND, 0);
    
    Intent MyIntent = new Intent(getApplicationContext(), BroadcastNotification.class);
    PendingIntent MyPendIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, MyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    
    AlarmManager MyAlarm = (AlarmManager) getSystemService(ALARM_SERVICE);
    MyAlarm.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmFor.getTimeInMillis(), MyPendIntent);
    

    In this example, onReceive() is as follows:

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("MyAPP", "onReceive() called");
    }
    

    When I run this, the following is logged at the the exact time requested:

    11-22 07:45:00.730 5833-5833/com.sap.myapplication D/MyAPP: onReceive() called
    

提交回复
热议问题