【发布时间】:2021-07-15 15:30:45
【问题描述】:
我有一个应用程序使用AlarmManager 在本地安排一堆通知(用户必须回答问卷)。该通知应在未来的某些时间点显示。
我这样安排通知:
private void scheduleNotification(Notification notification, int delay, int scheduleId, int notificationId) {
Intent notificationIntent = new Intent(context, NotificationPublisher.class);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, notificationId);
notificationIntent.putExtra(NotificationPublisher.INTENT, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, scheduleId, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, delay);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
意图由BroadcastReceiver 接收,该notify 在附加到意图的通知上调用。
public class NotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification-id";
public static String INTENT = "notification";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra(INTENT)) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
Notification notification = intent.getParcelableExtra(INTENT);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
}
}
}
到目前为止,这工作正常。我面临的问题是,如果应用程序当前未打开/显示,我只想显示通知。如果它是开放的,我想显示AlertDialog。
我知道最好只将通知的普通内容放入 Intent 中,并仅在应该显示它时构建它,并且我想稍后对其进行重构。
我的主要问题是,如何在我的广播接收器的onReceive 中确定应用当前是否正在显示以决定是否应该显示通知或警报?
或者是否有一种完全不同的方法可能效果更好(例如使用WorkManager)?
【问题讨论】:
标签: java android broadcastreceiver alarmmanager