Запускать несколько уведомлений каждый день

Я хочу запускать 5 уведомлений каждый день в определенное время (t1, t2, t3, t4, t5). Эти временные переменные мне приходится извлекать из JSON каждый день, потому что каждый день они имеют разные значения. Уведомление должно быть запущено, даже если приложение Android находится в фоновом режиме.

MyWorker Класс

public Result doWork() {
    sendNotification();
    return Result.SUCCESS;
}

public void sendNotification() {
    NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

    //If on Oreo then notification required a notification channel.
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel("default", "Default", NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

    NotificationCompat.Builder notification = new NotificationCompat.Builder(getApplicationContext(), "default")
            .setContentTitle("Hello")
            .setContentText("there")
            .setSmallIcon(R.mipmap.ic_launcher);

    notificationManager.notify(1, notification.build());
}

Мой логин

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    Window w = getWindow();
    w.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    w.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}

btnLogin = findViewById(R.id.login_button);

mWorkManager = WorkManager.getInstance();
mRequest2 = new PeriodicWorkRequest.Builder(MyWorker.class,15, TimeUnit.MINUTES).build();

btnLogin.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        mWorkManager.enqueue(mRequest2);
    }
});

}

Мне нужна помощь, чтобы уточнить. Должен ли я использовать двух воркеров, один для ежедневного получения данных из json в определенное время, а затем для запуска 5 уведомлений с определенным таймером для каждого или как я могу это решить. Я очень ценю ваше время. Спасибо!

====================================================================

Я тоже попробовал это через день, но не работает. Комбинированная служба, BroadcastReceiver и AlarmManager.

открытый класс MyService расширяет Service {

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent1 = new Intent(this, ShortTimeEntryReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent1,
            PendingIntent.FLAG_UPDATE_CURRENT);
    Calendar c = Calendar.getInstance();
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),AlarmManager.INTERVAL_FIFTEEN_MINUTES,
            pendingIntent);

    return START_STICKY;
}

}

И BroadcastReceiver

открытый класс ShortTimeEntryReceiver расширяет BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    sendNotification(context);
    context.startService(new Intent(context,MyService.class));

}

public void sendNotification(Context context) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel("default", "Default", NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

    NotificationCompat.Builder notification = new NotificationCompat.Builder(context, "default")
            .setContentTitle("Hello")
            .setContentText("there")
            .setSmallIcon(R.mipmap.ic_launcher);

    notificationManager.notify(1, notification.build());
}

}


person ArianitLu    schedule 19.04.2020    source источник


Ответы (1)


WorkManager не гарантирует, что ваш воркер будет запущен в точное время. Вам необходимо использовать AlarmManager с setExact().

Лично я бы рассмотрел возможность использования FCM с высоким приоритетом, отправляемый в приложение в нужное время с сервера.
Это намного более экономично для пользователя, и у вас гораздо меньше ограничений на современном Android из-за оптимизации заряда аккумулятора.

person pfmaggi    schedule 25.04.2020