1

Пытался реализовать уведомление, которое каждую неделю показывает уведомление, но оно не работает.

alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, AlarmReceiver.class);
    alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 1);

    long timeToStart = calendar.getTimeInMillis();
    if(System.currentTimeMillis() < timeToStart){
        timeToStart += 7 * 24 * 60 * 60 * 1000; // one day
    }
    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, timeToStart, AlarmManager.INTERVAL_DAY, alarmIntent);

Вообщем хочу реализовать уведомление, например каждый день в 12 часов дня, помогите это сделать.

2
  • Почитайте про JobScheduler 26 окт 2017 в 18:36
  • @SviatVolkov не совсем то что нужно JobScheduler для Android 5.0 (API 21) и выше , а мне нужно что работало на API 16
    – fcbarcafc
    27 окт 2017 в 13:01

2 ответа 2

3

Вот код для запуска AlarmManager, каждый день в 12 часов, который в свою очередь будет запускать ваш ресивер.

Calendar notifyTime = DateHelper.getTodayCalendarWithoutTime();
notifyTime.set(Calendar.HOUR_OF_DAY, 12);
notifyTime.set(Calendar.MINUTE, 0);
notifyTime.set(Calendar.SECOND, 0);

Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, notifyTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

Внутри ресивера проверяете условия запуска уведомления (нужно ли вообще запускать) и запускаете нужное уведомление или несколько уведомлений, в зависимости от ситуации.

public class NotificationReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (reminder != null) {
            // Запускаем уведомление
            MyNotification.notify(context, message, number);
        }
    }
}

Сами уведомления лучше хранить отдельно и рекомендую в Android Studio добавлять их через правую кнопку мыши - UI Component / Notification. Там очень правильные шаблоны для разных типов уведомлений с подробными комментариями.

1
  • Извините, А есть более подобная информация?
    –  Artsait
    24 фев 2018 в 17:21
2

У версиях АПИ 26 и выше, требует установку chanel. Предлагаю такой выход из ситуации:

            NotificationCompat.Builder builder =
                    new NotificationCompat.Builder(context)
                            .setSmallIcon(R.drawable.pict01)
                            .setContentTitle(Title)
                            .setContentText(MainText)
                            //.setLargeIcon(picture);
                            .setContentIntent(resultPendingIntent);
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

                CharSequence channelName = "c_name";
                int importance = NotificationManager.IMPORTANCE_LOW;
                NotificationChannel notificationChannel = new NotificationChannel("3260", channelName, importance);
                notificationChannel.enableLights(true);
                notificationChannel.setLightColor(Color.RED);
                notificationChannel.enableVibration(true);
                notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                notificationManager.createNotificationChannel(notificationChannel);
                builder.setChannelId(notificationChannel.getId());
            }

            Notification notification = builder.build();
            notificationManager.notify(a, notification);
2
  • А что за символ "а" в аргументе, на последней строчке? 14 фев 2021 в 11:46
  • @СергейБеляков notification id
    – Dewerro
    1 июл 2022 в 10:03

Ваш ответ

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

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