1

Я пытаюсь вызвать в определенное (8:25) время с интервалом в день уведомление, оно работает иногда, то есть бывают дни когда она вообще не работает MainActivity класс:

private NotificationManager nm;
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
boolean alarmUp = (PendingIntent.getBroadcast(MainActivity.this, 0, new Intent
                (this, NotificationReceiver.class), PendingIntent.FLAG_NO_CREATE) != null);
        Toast.makeText(this, "alarmUp = " + alarmUp, Toast.LENGTH_SHORT).show();
        if (!alarmUp) {
            nm = (NotificationManager) MainActivity.this.getSystemService(Context.NOTIFICATION_SERVICE);

            Calendar calendar1Notify = Calendar.getInstance();
            calendar1Notify.set(Calendar.HOUR_OF_DAY, 8);
            calendar1Notify.set(Calendar.MINUTE, 25);
            calendar1Notify.set(Calendar.SECOND, 0);
            Toast.makeText(MainActivity.this, "alarmManager", Toast.LENGTH_SHORT).show();

            Intent intent1 = new Intent(MainActivity.this, NotificationReceiver.class);
            PendingIntent pendingIntent1 = PendingIntent.getBroadcast(MainActivity.this, 0, intent1,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar1Notify.getTimeInMillis(),
                    AlarmManager.INTERVAL_DAY, pendingIntent1);
        }
}

NotificationReceiver класс:

public class NotificationReceiver extends BroadcastReceiver {
    private NotificationManager nm;
    private final int NOTIFICATION_ID = 100;
    private static final String CHANNEL_ID = "CHANNEL_ID";

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    public void onReceive(Context context, Intent intent) {
        nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        BitmapFactory.Options options = new BitmapFactory.Options();
        Intent intent2 = new Intent(context.getApplicationContext(), MainActivity.class);
        PendingIntent pendingIntent2 = PendingIntent.getActivity(context.getApplicationContext(), 0, intent2, PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context.getApplicationContext(),CHANNEL_ID);
        builder
                .setContentIntent(pendingIntent2)
                .setSmallIcon(R.drawable.fav_btn_icon)
                .setLargeIcon(BitmapFactory.decodeResource(context.getApplicationContext().getResources(), R.drawable.fav_btn_icon, options))
                .setTicker("Новое уведомление")
                .setAutoCancel(true)
                .setPriority(PRIORITY_HIGH)
                .setWhen(System.currentTimeMillis())
                .setContentTitle("Пора зарядиться энергией!")
                .setContentText("Попытайся вытащить полезный урок");
        Notification notification = builder.build();
        notification.defaults = Notification.DEFAULT_SOUND;
        createChannelIfNeeded(nm);
        nm.notify(NOTIFICATION_ID, notification);
    }
    public static void createChannelIfNeeded(NotificationManager manager) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_ID, NotificationManager.IMPORTANCE_DEFAULT);
            manager.createNotificationChannel(notificationChannel);
        }
    }
}

Я когда на своем телефоне (не на эмуляторе меняю время на 8:25) она иногда срабатывает, а иногда нет. В чем причина? Как сделать так чтобы она срабатывала всегда в указанное время? А а не когда попало. Спасибо. Или если есть способы получше подскажите пожалуйста

2
  • Если вы запустите приложение после 8.25 будильник не сработает первый раз, потому что вы берете календарь и откатываете его назад. К тому же после 19 API setRepeating не будет точно срабатывать, скорее всего ни а каком 8.25 речь не идет
    – Style-7
    19 янв 2021 в 16:01
  • А что будет точно работать? Что мне использовать? 19 янв 2021 в 16:33

0

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

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