【发布时间】:2018-09-13 14:28:55
【问题描述】:
假设您在应用处于前台时触发了 FCM 通知。我可以在用户关闭应用程序时安排通知,而不是在前台显示通知吗?有可能吗?
【问题讨论】:
-
您想在应用处于后台时接收通知?
标签: android firebase firebase-cloud-messaging android-notifications
假设您在应用处于前台时触发了 FCM 通知。我可以在用户关闭应用程序时安排通知,而不是在前台显示通知吗?有可能吗?
【问题讨论】:
标签: android firebase firebase-cloud-messaging android-notifications
您可以使用生命周期扩展来检测您的应用程序何时进入后台。
将此添加到您的模块build.gradle 文件中
dependencies {
implementation "android.arch.lifecycle:extensions:1.1.0"
}
在您的应用程序类中,
class MyApplication : Application(), LifecycleObserver {
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onAppBackgrounded() {
Log.d("MyApp", "Application sent to background")
// you can save a value here and check it later
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onAppForegrounded() {
Log.d("MyApp", "App brought to foreground")
// don't forget to change the value stored in onAppBackgrounded to detect the app is again in foreground
}
}
现在在您的 FirebaseMessagingService 类中,在 onMessageReceived 中,您可以使用之前存储的值来检查应用程序是否在后台
【讨论】:
正在发送的 fcm 数据应如下所示
{
"to" : “/topics/global“,
"notification" : {
"body" : "Some body",
"title" : "Some title",
},
"data" : {
“body" : “Some body“,
“title" : “Some title“,
“key" : “value"
}
}
使用remoteMessage.getData()代替remoteMessage.getNotification(),无论应用在前台还是后台,收到通知都会显示。
public void onMessageReceived(RemoteMessage remoteMessage){
sendNotification(remoteMessage.getData());
}
public void sendNotification(HashMap<String, String> data){
String title = data.get("title");
String message = data.get("message");
}
【讨论】: