我已经和它斗争了很长一段时间了,我正在使用闹钟管理器来安排闹钟,我在我的清单文件中声明了一个接收器。当应用程序运行或在后台运行时,警报和接收器按预期工作,我无法在用户关闭应用程序后触发警报。我本质上只是想在我的应用程序中进行本地通知。没有其他"答案"这里有很多帮助。应用程序关闭后是否可以触发本地通知?
public static void writtenGoalsNotification(Context context) {
final int _id = 15;
pref = context.getSharedPreferences("userpref", 0);
Notification notification = getNotification("Don't forget to write your daily goals!", context, "none", "Goals");
Intent notificationIntent = new Intent(context, NotificationReceiver.class);
notificationIntent.putExtra(NotificationReceiver.NOTIFICATION_ID, "written goals notification");
notificationIntent.putExtra(NotificationReceiver.NOTIFICATION, notification);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, _id, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Integer hour = pref.getInt(NotificationKeys.Goals.ReminderTime.hour, 10);
Integer minute = pref.getInt(NotificationKeys.Goals.ReminderTime.minute, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.MILLISECOND, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000 * 60 * 60 * 24, pendingIntent);
}
这是我的接收器,
public class NotificationReceiver extends WakefulBroadcastReceiver {
public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
startWakefulService(context, intent);
WakeLocker.acquire(context);
WakeLocker.release();
}
}
这是我的清单,
<receiver
android:name=".Controllers.NotificationReceiver"
</receiver>
答案 0 :(得分:0)
广告接收器在API级别26中已弃用。 你没有得到alram的主要原因是因为你正在使用的App的过程已经完成并且如果设备中的内存很少则被清除。相反,您应该使用服务,以便它具有更高的优先级。 所以为此,我建议您使用BroadcastReceiver类而不是WakeupBroadcastReceiver,因为android文档说这个 - (从接收广播开始提供服务通常是不安全的,因为此时您无法保证您的应用程序处于前台,因此可以这样做。)
因此,您的设置alram的过程可能会被破坏。所以使用BroadcastReceiver。 在清单中这样做
<receiver
android:name=".NotificationReceiver"
</receiver>