如何在特定时间后在Android中显示通知

时间:2019-01-26 18:51:25

标签: java android android-studio

我正在开发基于某些通知的应用程序,通过该应用程序,用户可以执行我想显示通知的操作,并在通知之后添加5分钟的添加时间来显示下一个通知。并在应用关闭时在后台运行计时器进程。

 public long Time = 3600;
 private NotificationManagerCompat notificationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        notificationManager = NotificationManagerCompat.from(this);
        Timer();

    }


    public void Timer() {

        for (long i = Time; i < 86400000; i = i += 60000) {

            new CountDownTimer(1000, i) {
                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    ShowNotification();


                }
            }.start();
        }


    }

    public void ShowNotification() {
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
                .setContentTitle("Example")
                .setContentText("Example Action")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setCategory(NotificationCompat.CATEGORY_REMINDER)
                .build();

        notificationManager.notify(1, notification);


    }

1 个答案:

答案 0 :(得分:1)

在这种情况下,请尝试使用AlarmReceiver。

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                    notificationManager.notify(0, notification);
                    AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.HOUR, 2);
                    Intent intent = new Intent("android.action.DISPLAY_NOTIFICATION");
                    intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                    PendingIntent broadcast = PendingIntent.getBroadcast(context, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), broadcast);