Android Studios Alarm Manager 應用程式已關閉



>我已经为此斗争了一段时间,我正在使用警报管理器来安排警报,我在清单文件中声明了一个接收器。警报和接收器在应用程序运行时或在后台按预期工作,用户关闭应用程序后,我无法触发警报。我基本上只是想在我的应用程序中有本地通知。这里的其他"答案"都没有多大帮助。关闭应用后是否可以触发本地通知?

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>

广播接收器在 API 级别 26 中已弃用。 您没有收到alram的主要原因是因为,如果设备内存不足,则您使用的应用程序过程已完成并清除。相反,您应该使用服务,以便它具有更高的优先级。 因此,为此,我建议您使用BroadcastReceiver类而不是WakeupBroadcastReceiver,因为android文档是这样说的- (从收到广播开始启动服务通常不安全,因为你无法保证你的应用此时位于前台,因此允许这样做。

因此,您设置alram的过程可能会被破坏。所以使用BroadcastReceiver。 在清单中执行此操作

<receiver
android:name=".NotificationReceiver"
</receiver>

最新更新