Ошибка при отображении уведомлений на будущую дату и время в Android studio

#android #datetime #android-notifications #alarmmanager #notificationmanager

Вопрос:

Я пытаюсь отображать уведомления по введенным пользователем дате и времени, но уведомления не отображаются. Я пробовал разные подходы, но ничего не изменилось — уведомления просто не отображаются.

Моя основная деятельность —

 public class MainActivity extends  AppCompatActivity   {
private static final int NOTIFICATION_ID = 3;
Switch switch_btn;
EditText date_ed, time_ed;
Button button;
int y,m,d,h,min;
Calendar c;

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

    switch_btn = findViewById(R.id.switch_btn);
    date_ed = findViewById(R.id.date_ed);
    time_ed = findViewById(R.id.time_ed);

            switch_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    c = Calendar.getInstance();
                    y = c.get(Calendar.YEAR);
                    m = c.get(Calendar.MONTH);
                    d = c.get(Calendar.DAY_OF_MONTH);
                    h = c.get(Calendar.HOUR_OF_DAY);
                    min = c.get(Calendar.MINUTE);
                    DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            date_ed.setText(dayOfMonth   "-"   (monthOfYear   1)   "-"   year   "  ");
                            c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                            c.set(Calendar.MONTH, monthOfYear 1);
                            c.set(Calendar.YEAR, year);
                        }
                    }, y, m, d);

                    datePickerDialog.show();

                    TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {

                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                            time_ed.setText("  "   hourOfDay   ":"   minute);
                            c.set(Calendar.HOUR_OF_DAY, hourOfDay);
                            c.set(Calendar.MINUTE, minute);
                            c.set(Calendar.SECOND, 0);
                            c.set(Calendar.MILLISECOND, 0);
                        }
                    }, h, min, false);
                    timePickerDialog.show();


                }

            });

    button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onClick(View v) {
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
            intent.putExtra("notificationId",NOTIFICATION_ID);
            PendingIntent pintent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
            long trigger = c.getTimeInMillis();
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, trigger, pintent);
            Toast.makeText(getApplicationContext(), "set", Toast.LENGTH_SHORT).show();
        }
    });


}

private void createNotificationChannel(){
    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel channel = new NotificationChannel("notification", name, importance);
        channel.setDescription(description);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}
 

}

Мой класс по приему будильника —

 public class AlarmReceiver extends BroadcastReceiver {
private static final int NOTIFICATION_ID = 3;

@Override
public void onReceive(Context context, Intent intent) {
    Intent it = new Intent(context, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingintent = PendingIntent.getActivity(context, 0, it, 0);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "notification");
    builder.setContentTitle("You have an alert")
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setContentText("Open to view")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_EVENT)
            .setContentIntent(pendingintent)
            .setAutoCancel(true);

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);
    nm.notify(NOTIFICATION_ID, builder.build());


}}
 

Мой Manifest.xml —

  <receiver android:name=".AlarmReceiver"/>
 

Пожалуйста, дайте мне знать, в чем может быть проблема в этом случае.