【发布时间】:2017-08-04 16:42:17
【问题描述】:
我已经为此奋斗了很长时间,我正在使用警报管理器来安排警报,我在清单文件中声明了一个接收器。在应用程序运行或在后台运行时,警报和接收器按预期工作,在用户关闭应用程序后,我无法触发警报。我本质上只是想在我的应用程序中添加本地通知。这里的其他“答案”都没有太大帮助。应用关闭时是否可以触发本地通知?
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>
【问题讨论】:
-
显示错误日志
-
我能得到一些更具描述性的东西吗?该代码没有产生任何错误,通知在应用程序运行或后台正确发生。问题是,一旦应用程序关闭,警报或接收器都会被破坏。
-
我误解了这个问题。接受我的道歉。我认为您需要扩展广播接收器....我从未使用过唤醒广播接收器。希望其他人可以插话来帮助你。
-
尝试使用 IntentService 而不是 BroadcastReceiver。
-
或者尝试在
receiver标签中添加android:exported="true"。
标签: android alarmmanager