在特定时间自动通知

时间:2018-12-03 23:21:40

标签: java android time notifications calendar

我要发出的通知是要在每天的确切同一时间发出通知。我想保持简单,因为我还是个初学者。

这是我的MainActivity:

private static final int notificationId = 4242;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initChannels(this);

    // Create an explicit intent for an Activity in your app
    Intent intent = new Intent(this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "default")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle("This is the title")
            .setContentText("This is the body of the notification.")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            // Set the intent that will fire when the user taps the notification
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

    // notificationId is a unique int for each notification that you must define
    notificationManager.notify(notificationId, mBuilder.build());
}

public void initChannels(Context context) {
    if (Build.VERSION.SDK_INT < 26) {
        return;
    }
    NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationChannel channel = new NotificationChannel("default",
            "Channel name",
            NotificationManager.IMPORTANCE_DEFAULT);
    channel.setDescription("Channel description");
    notificationManager.createNotificationChannel(channel);
}

我的代码当前执行的操作完全没有。我相信代码在我启动应用程序时应该发送通知,但这也没有发生。我认为第一步至少是使通知生效。然后将其设置为在特定时间(例如上午9点)工作。

编辑:该代码已修复,至少可以正常工作。现在,当我进入应用程序时,我将收到通知,如原计划那样。我的问题的第二部分是如何使其每天在同一时间关闭?

1 个答案:

答案 0 :(得分:0)

您可以使用Alarm Manager

但是,为了减少电池消耗,Alarm Manager不会在准确的时间发出警报,并且此策略在Android平台上有所不同。

您可以找到有关警报管理器Here

的更多信息
  

从API 19(Build.VERSION_CODES.KITKAT)开始,警报传递是不准确的:操作系统将转移警报,以最大程度地减少唤醒和电池消耗。

相关问题