简体   繁体   中英

How can I set a notification for specific time & date set by date & time picker dialog in Android

I am trying to trigger notifications on specific dates & times set using with DatePicker & Timepicker Dialog. I have tried the below code but it shows notifications at the current time while clicking the "setTime" button before setting time. I have tried many ways using the below code but doesn't seem to work.

MainActivity Class with Date & Time Picker Dialog

public class MainActivity extends AppCompatActivity {

    private TextView showTime;
    private Button setTime;

    //1.Calender Instance
    Calendar calendar = Calendar.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showTime = findViewById(R.id.textViewTime);
        setTime = findViewById(R.id.buttonSet);

        setTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                    showDateTimeDialog();


            }
        });

    }

    //--------->>Date and Time picker Method--------->>>
    private void showDateTimeDialog() {


        DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {

                //3 Set DATE
                calendar.clear();
                calendar.set(Calendar.YEAR,year);
                calendar.set(Calendar.MONTH,month);
                calendar.set(Calendar.DAY_OF_MONTH,dayOfMonth);


                TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) {


                        //SetTime
                        calendar.set(Calendar.HOUR_OF_DAY,hourOfDay);
                        calendar.set(Calendar.MINUTE,minute);



                        // if set date & time has already passed, increment day by 1
                        if (calendar.getTimeInMillis() <= System.currentTimeMillis()) {
                            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
                        }

                        DateFormat simpleDateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, Locale.getDefault());
                        //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE,d-mmm-yyy HH:mm a");

                        showTime.setText(simpleDateFormat.format(calendar.getTime()));

                    }
                };
                //5
                new TimePickerDialog(MainActivity.this, timeSetListener, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), false).show();
            }
        };


        //2.
        new DatePickerDialog(MainActivity.this, dateSetListener,calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)).show();

        //----------->>Setting Notification------------------>

        Intent intent = new Intent(getApplicationContext(),NotificationReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),100,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
        //alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),1000,pendingIntent);

    }

}

Notification receiver class

public class NotificationReceiver extends BroadcastReceiver {

    public final String CHANNEL_ID = "1";

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onReceive(Context context, Intent intent) {

        
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID,"1",
                NotificationManager.IMPORTANCE_DEFAULT);

        
        NotificationManager manager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
       
        manager.createNotificationChannel(channel);

        
        Notification.Builder builder = new Notification.Builder(context, CHANNEL_ID);
        builder.setSmallIcon(R.drawable.ic_baseline_add_alert_24) // Setting icon
                .setContentTitle("Title")//Notification title
                .setContentText("This is Periodic Notification Alert") //Set notification message
                .setPriority(Notification.PRIORITY_DEFAULT);

        
        NotificationManagerCompat compat = NotificationManagerCompat.from(context);
        
        compat.notify(1, builder.build());

    }
}

Solved the problem.

Added condition onset Time, and call setAlarm method

                    Date setTime = calendar.getTime();
                    if(setTime.compareTo(currentTime) <= 0){
                        Toast.makeText(MainActivity.this, "Invalid time, Set future time", Toast.LENGTH_SHORT).show();
                    }else {

                        showTime.setText(simpleDateFormat.format(calendar.getTime()));
                        setAlarm(calendar);

                    }

And Moved the setAlarm in different method.

private void setAlarm(Calendar calendar){

    Intent intent = new Intent(getApplicationContext(),NotificationReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),100,
            intent, 0); //PendingIntent.FLAG_UPDATE_CURRENT
    Log.d("alarm", "showDateTimeDialog: alarm time" + calendar.getTimeInMillis());
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
    //alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),1000,pendingIntent);


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM