如何在特定日期和特定时间设置通知?

ioekq8ef  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(534)

这个问题在这里已经有答案了

android将日期和时间转换为毫秒(10个答案)
5个月前关门了。
我想做一个通知出现在一个特定的日期在一个特定的时间,因为我写在标题。现在我的警报在按下按钮10秒后出现。如果我需要确定一个具体的日期,我也需要这样做吗?我需要将日期转换为毫秒并给出这个参数?这是我的密码:

package com.example.timeman;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class ReminderBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "notify")
            .setSmallIcon(R.drawable.ic_baseline_close_24)
            .setContentTitle("Salamabuliy")
            .setContentText("TextNotif")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            ;
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

    notificationManager.notify(200, builder.build());
}

}
和onclick方法:

public void onClick(View view) {
            Intent intent = new Intent(getActivity(), ReminderBroadcast.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);

            AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);

            long timeAtButtonClick = System.currentTimeMillis();

            long tenSecondsInMillis = 1000*10;

            alarmManager.set(AlarmManager.RTC, timeAtButtonClick + tenSecondsInMillis, pendingIntent);
            //displayNotification();
            OpenThis(view);
        }
2g32fytz

2g32fytz1#

一种选择是以毫秒为单位找出从现在到你希望它出现的日期之间的持续时间。例如;

LocalDateTime now = LocalDateTime.now();

LocalDateTime end = now.plusSeconds(10); // end date can be specific, this is an example

Duration difference = Duration.between(now, end);

long differenceMillis = difference.toMillis();
kqqjbcuj

kqqjbcuj2#

使用 Instant#toEpochMilli() 以及 Instant#plusSeconds 如下图所示:

import java.time.Instant;

import java.time.Instant;

public class Main {
    public static void main(String[] args) {
        Instant now = Instant.now();
        System.out.println(now.toEpochMilli());

        // After 10 seconds
        Instant after10SecFromNow = now.plusSeconds(10);
        long millisAfter10Sec = after10SecFromNow.toEpochMilli();
        System.out.println(millisAfter10Sec);

        // alarmManager.set(AlarmManager.RTC, millisAfter10Sec, pendingIntent);
    }
}

输出:

1597837345043
1597837355043

相关问题