首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Android中,当通知到来时,Oreo 8.0应用程序将从后台进入前台

在Android中,当通知到来时,Oreo 8.0应用程序将从后台进入前台
EN

Stack Overflow用户
提问于 2018-05-22 23:14:18
回答 1查看 878关注 0票数 1

当通知到来时,我的应用程序正在进入前台,而应用程序处于后台状态,但这种行为不会在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());
EN

回答 1

Stack Overflow用户

发布于 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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50471133

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档