有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

应用程序未运行时的java推送计划通知

首先:这个问题和我的上一个问题非常相似,但答案对我没有帮助

我正在制作一个待办应用程序。我一直在推送通知(即使应用程序没有运行)。 我的目标是推送一个关于待办任务的通知,即使应用程序没有运行

例如。 我在x/y/2021的mm:hh做了一个关于家庭作业的新任务。应用程序必须在该时刻推送通知,即使应用程序未运行

计划(延迟10只是为了调试):

    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);

阶级扩展工作者:

@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();
}

共 (1) 个答案

  1. # 1 楼答案

    老实说,我不读你的代码,但看看workManager(因为它是为这些东西设计的):

    Android workManager文档:

    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.

    工作经理:https://developer.android.com/topic/libraries/architecture/workmanager

    例如(我想这就是你想要的):https://medium.com/@ifr0z/workmanager-notification-date-and-time-pickers-aad1d938b0a3