0

У меня есть приложение с заметками. Я добавил туда уведомления (которые появляются в строке состояния). Для теста я сделал так, чтобы при нажатии на кнопку "Green" приложение не только меняло фон, но и отослало уведомление пользователю. Но мне бы хотелось сделать так, чтобы уведомление отсылалось пользователю не по нажатию кнопку, а автоматически, в определённое время(например, в 17:00) , даже если он не открыл приложение. Как мне это реализовать? Для этого я заранее подготовил BootCompletedReceiver чтобы автоматически запускать приложение после загрузки устройства. Код ресивера и отправки уведомления будет ниже.

BootCompletedReceiver:

public class BootCompletedReceiver extends BroadcastReceiver {

    public BootCompletedReceiver() {
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {

        }
    }
}

Код для отправки уведомления:

...

public void onClickGreen(View view) { 
        Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
        } else {
            
            v.vibrate(500);
        }
        Intent notificationIntent = new Intent(Options.this, Options.class);
        PendingIntent contentIntent = PendingIntent.getActivity(Options.this,
                0, notificationIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(Options.this, CHANNEL_ID)
                        .setSmallIcon(R.drawable.ikon_for_calendar_1)
                        .setContentTitle("Напоминание")
                        .setContentText("Пора проверить заметки!")
                        .setSound(defaultSoundUri)
                        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                        .setContentIntent(contentIntent)

                        .setAutoCancel(true); // автоматически закрыть уведомление после нажатия



        NotificationManagerCompat notificationManager =
                NotificationManagerCompat.from(Options.this);
        notificationManager.notify(NOTIFY_ID, builder.build());


    }
3
  • 2
    Правильно такие вещи делать через push notification с сервера. Чтобы приложение не болталось в памяти и не жрало батарею только ради того чтобы однажды какое-то уведомление отобразить. Вместо этого сервер отправить пуш когда надо, система запустит приложение и отобразит уведомление. 8 янв 2022 в 11:17
  • 2
    Понятно, что с пушами все усложняется, без них можно все сделать с помощью WorkManager, он умеет пережить перезагрузки телефона и все такое. developer.android.com/topic/libraries/architecture/workmanager 8 янв 2022 в 11:19
  • 1
    Делайте через AlarmManager
    – Style-7
    8 янв 2022 в 12:05

1 ответ 1

1

Используйте alarm manager и поместите свое уведомление в класс NotifyService

   Intent myIntent = new Intent(Current.this , NotifyService.class);     
   AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
   pendingIntent = PendingIntent.getService(ThisApp.this, 0, myIntent, 0);
   Calendar calendar = Calendar.getInstance();
   calendar.set(Calendar.HOUR_OF_DAY, 12);
   calendar.set(Calendar.MINUTE, 00);
   calendar.set(Calendar.SECOND, 00);
   alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 
   calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY , pendingIntent);  
   //set repeating every 24 hours

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.