当通知到来时,我的应用程序正在进入前台,而应用程序处于后台状态,但这种行为不会在killed状态下发生。这不是在奥利奥下面发生的。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this,CHANNEL_ID)
.setSmallIcon(R.drawable.tracking_app_logo)
.setContentTitle(getString(R.string.app_name))
.setContentText("Uploading database...")
.setContentIntent(pendingIntent)
.setAutoCancel(false)
.setChannelId(CHANNEL_ID)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_HIGH);
startForeground(102, mBuilder.build());
发布于 2018-05-22 23:26:42
发生的情况是,您正在自己的活动上下文中创建通知,并且从未从后台服务启动它,因此如果您没有终止应用程序,您将能够看到通知,因为上下文仍然是活动的,并且可以创建通知。
您应该使用AlarmManager
来计划您的通知,因为您在自己的活动上下文中使用它,我建议您阅读有关AlarmManager
服务的信息以及如何使用通知完成它。
关于如何实现这一点的一篇好文章可以在这里找到http://droidmentor.com/schedule-notifications-using-alarmmanager/
它的工作原理是基本的:
首先,您需要设置后台服务(如AlarmManager
)在后台启动应用程序的通知
AlarmManager
将设置通知的时间,即使应用程序被终止,它也会启动您的通知,因为AlarmManager
是在系统后台运行的服务。
另一个技巧是将Firebase云消息传递服务与NotificationCompat结合使用;您只需在清单中实现该服务即可在后台运行通知
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
查看Firebase消息传递文档:https://firebase.google.com/docs/cloud-messaging/android/client
https://stackoverflow.com/questions/50471133
复制相似问题