【问题标题】:How to show FCM notification only when user closes the app in Android? [closed]仅当用户在 Android 中关闭应用程序时如何显示 FCM 通知? [关闭]
【发布时间】:2018-09-13 14:28:55
【问题描述】:

假设您在应用处于前台时触发了 FCM 通知。我可以在用户关闭应用程序时安排通知,而不是在前台显示通知吗?有可能吗?

【问题讨论】:

  • 您想在应用处于后台时接收通知?

标签: android firebase firebase-cloud-messaging android-notifications


【解决方案1】:

您可以使用生命周期扩展来检测您的应用程序何时进入后台。

  1. 将此添加到您的模块build.gradle 文件中

    dependencies {
        implementation "android.arch.lifecycle:extensions:1.1.0"
    }
    
  2. 在您的应用程序类中,

    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 
       }
    }
    
  3. 现在在您的 FirebaseMessagingService 类中,在 onMessageReceived 中,您可以使用之前存储的值来检查应用程序是否在后台

【讨论】:

  • 谢谢@basil ...这就是我要找的东西
  • 最欢迎@topsecret,你能作为正确的答案进行营销吗?
【解决方案2】:

正在发送的 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");  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-19
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 2019-02-02
    • 2017-04-11
    相关资源
    最近更新 更多