如何为 Android 中的日期和时间选择器对话框设置的特定时间和日期设置通知

Posted

技术标签:

【中文标题】如何为 Android 中的日期和时间选择器对话框设置的特定时间和日期设置通知【英文标题】:How can I set a notification for specific time & date set by date & time picker dialog in Android 【发布时间】:2022-01-20 16:00:58 【问题描述】:

我正在尝试在使用 DatePicker 和 Timepicker 对话框设置的特定日期和时间触发通知。 我已经尝试了下面的代码,但它会在当前时间显示通知,同时在设置时间之前单击“setTime”按钮。 我用下面的代码尝试了很多方法,但似乎没有用。

带有日期和时间选择器对话框的 MainActivity 类

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

    


通知接收类

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

    

【问题讨论】:

【参考方案1】:

解决了这个问题。

增加条件开始时间,并调用setAlarm方法

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

                    

并以不同的方法移动了 setAlarm。

private void setAlarm(日历)

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



【讨论】:

以上是关于如何为 Android 中的日期和时间选择器对话框设置的特定时间和日期设置通知的主要内容,如果未能解决你的问题,请参考以下文章

一个对话框中的 Android 日期时间选择器

如何为带有 $ 符号的 Class 的元素编写选择器

简单的 Android 目录选择器 - 如何?

Android:时间选择器和日期选择器在同一个对话框中

如何为 ui-bootstrap 日期选择器创建 angularJs 包装器指令?

仅包含日期和月份的Android日期选择器