如何仅当用户在 Android 中关闭应用程序时才显示 FCM 通知?
How to show FCM notification only when user closes the app in Android?
假设您在应用程序位于前台时触发了 FCM 通知。我可以在用户关闭应用程序时安排通知,而不是在前台显示通知吗?可以吗?
您可以使用生命周期扩展来检测您的应用程序何时进入后台。
将此添加到您的模块 build.gradle
文件
dependencies {
implementation "android.arch.lifecycle:extensions:1.1.0"
}
在您的申请中 class、
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 class 中,在 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");
}
假设您在应用程序位于前台时触发了 FCM 通知。我可以在用户关闭应用程序时安排通知,而不是在前台显示通知吗?可以吗?
您可以使用生命周期扩展来检测您的应用程序何时进入后台。
将此添加到您的模块
build.gradle
文件dependencies { implementation "android.arch.lifecycle:extensions:1.1.0" }
在您的申请中 class、
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 class 中,在
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");
}