我尝试制作在特定时间推送一次的离线推送通知。 以下是我的日历和AlarmManager设置:
Intent intent = new Intent(getApplicationContext(), Notification_receiver.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(getApplicationContext(), 101, intent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(getApplicationContext(), 102, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar push1 = Calendar.getInstance();
Calendar push2 = Calendar.getInstance();
push1.set(2017, Calendar.JULY, 1);
push1.set(Calendar.HOUR_OF_DAY, 20);
push1.set(Calendar.MINUTE, 22);
push1.set(Calendar.SECOND, 30);
push2.set(2017, Calendar.JULY, 1);
push2.set(Calendar.HOUR_OF_DAY, 20);
push2.set(Calendar.MINUTE, 28);
push2.set(Calendar.SECOND, 30);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, push1.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent1);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, push2.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent2);
我的通知类:
public class Notification_receiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context, RepeatingActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent1 = PendingIntent.getActivity(context, 101, repeating_intent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent2 = PendingIntent.getActivity(context, 102, repeating_intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder1 = new NotificationCompat.Builder(context).setContentIntent(pendingIntent1)
.setSmallIcon(R.drawable.onusicijadi_icon)
.setContentTitle("FIRST")
.setContentText("FIRST NOTIFICATION")
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true);
notificationManager.notify(103, builder1.build());
NotificationCompat.Builder builder2 = new NotificationCompat.Builder(context).setContentIntent(pendingIntent2)
.setSmallIcon(R.drawable.onusicijadi_icon)
.setContentTitle("SECOND")
.setContentText("SECOND NOTIFICATION")
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true);
notificationManager.notify(104, builder2.build());
}}
RepeatingActivity.class只是:
public class RepeatingActivity extends AppCompatActivity{
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_program);
}
此代码在20:22和20:28发送通知,显然我希望它分开。例如,一个通知在20:22进行,另一个在20:28进行。 在为期3天的节日期间,我将需要大约30个通知。
答案 0 :(得分:0)
注意:从API 19开始,所有重复警报都不准确。如果你的 应用程序需要精确的交付时间,然后必须使用一次性 确切的警报,每次重新安排,如上所述。遗产 targetSdkVersion早于API 19的应用程序将 继续发出所有警报,包括重复警报, 确切地对待。
您可以在AlarmManager docs上找到更多信息,如果您仍在使用AlarmManager,则解决方案可能是setExact
或setExactAndAllowWhileIdle
。
使用时请小心,如果您在短时间内收到多个通知,则可以考虑使用服务。