简体   繁体   中英

Push scheduled notifications when app is not running

First of all: this question is very similar to my last one, but answer couldn't help me...

I am making a To-Do app. I got stuck on pushing notifications (even when app is not running). My achieve is to push a notification about a to-do task, even if the app is not running.

eg I make a new to-do task about homework on x/y/2021 at mm:hh. App must push a notification at that moment, even while app is not running

Scheduling (delay as 10 is just to debugging):

    OneTimeWorkRequest notificationWorker = new OneTimeWorkRequest.Builder(NotificationWorker.class)
            .setInitialDelay(10, TimeUnit.SECONDS)
            .setInputData(new Data.Builder().putString("title", "Note").build()).build();

    WorkManager workManager = WorkManager.getInstance(this);
    workManager.enqueue(notificationWorker);

Class extending Worker:

@NonNull
@Override
public Result doWork() {

    NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

    String date = getInputData().getString("date");
    String time = getInputData().getString("time");
    String title = getInputData().getString("title");
    String description = getInputData().getString("description");
    int delay = getInputData().getInt("delay", 0);

    Notification notification = new NotificationCompat.Builder(getApplicationContext(), "note")
            .setSmallIcon(R.mipmap.logo)
            .setContentTitle(title)
            .setContentInfo(date + " at " + time)
            .setContentText(description)
            .build();

    notificationManager.notify(1, notification);

    return Result.success();
}

Honestly i dont read your code but take a look at workManager(because it's designed for these things):

Android workManager documentation:

WorkManager is an API that makes it easy to schedule deferrable, asynchronous tasks that are expected to run even if the app exits or the device restarts. The WorkManager API is a suitable and recommended replacement for all previous Android background scheduling APIs, including FirebaseJobDispatcher, GcmNetworkManager, and Job Scheduler. WorkManager incorporates the features of its predecessors in a modern, consistent API that works back to API level 14 while also being conscious of battery life.

workManager: https://developer.android.com/topic/libraries/architecture/workmanager

example(i think this is what u want): https://medium.com/@ifr0z/workmanager-notification-date-and-time-pickers-aad1d938b0a3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM