【发布时间】:2022-01-02 12:04:55
【问题描述】:
我的应用程序中的通知有问题。我想为一天中的不同时间设置多个通知。例如,让我们以 8 点、12 点和 23 点为例。但每天只有23点触发。我的代码有什么问题,即使应用程序被杀死,它还能工作吗? 这是在我的活动中设置警报的代码
public void myAlarm(int hour, int minute) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
Intent intent = new Intent(getApplicationContext(), Reminder.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
这就是我在 onCreate 中写的
myAlarm(8, 0);
myAlarm(12, 0);
myAlarm(23, 0);
这是我的接收器
public class Reminder extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent in = new Intent(context, MySecoundActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "Reminder")
.setSmallIcon(R.drawable.bell)
.setContentTitle("Notification!")
.setContentText("Text of notification")
.setColor(0xfb3ff)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat notificationMngr = NotificationManagerCompat.from(context);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Reminder";
String description = "reminder channel";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel("Reminder", name, importance);
channel.setDescription(description);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
notificationMngr.notify(200, builder.build());
}
接收器在 android manifest 中
<receiver android:name=".Reminder"/>
【问题讨论】:
标签: java android notifications android-notifications alarmmanager