是否可以设置Android通知或以后在应用未运行时触发的日期和时间?

时间:2014-06-25 23:43:22

标签: java android notifications

根据我的阅读,似乎这样的代码需要应用程序在线程中运行,直到通知触发。我需要在稍后的日期和时间触发通知,以便用户看到通知,就像任何其他通知一样,然后单击它并打开一个活动,传入一些数据,以便应用知道该做什么。

如何在没有应用程序一直运行的情况下几天后发出此通知?

我是否等待完成此操作?

long millis = 60000;
myNotification.wait(millis);

这是我的代码立即触发

NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getActivity())
.setSmallIcon(R.drawable.star)
.setContentTitle("How was " + me.getString("EventTitle") + "?")
.setContentText("Click here to leave your review");

Intent resultIntent = new Intent(getActivity(), SetupActivity.class);

PendingIntent resultPendingIntent =
PendingIntent.getActivity(
getActivity(),
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);

    mBuilder.setContentIntent(resultPendingIntent);

    int mNotificationId = me.getInt("EventID");
    // Gets an instance of the NotificationManager service
    NotificationManager mNotifyMgr = 
            (NotificationManager) getActivity().getSystemService(getActivity().NOTIFICATION_SERVICE);


    // Builds the notification and issues it.
    mNotifyMgr.notify(mNotificationId, mBuilder.build());

1 个答案:

答案 0 :(得分:5)

正如A - C所写,使用AlarmManager安排在您所需的时间调用PendingIntent。您可能会使用RTC_WAKEUP警报,这意味着“时间基于System.currentTimeMillis(),如Calendar使用”和“让设备退出睡眠模式”。使用广播PendingIntent,如果您不需要执行任何磁盘或网络I / O来获取要用于的信息,那么您的Notification代码可以进入onReceive()方法Notification本身。

请注意,在Android 4.4中,AlarmManager的规则发生了一些变化。您需要在早期Android版本的Android 4.4及setExact()上使用set()