简体   繁体   English

从FirebaseMessagingService类调用活动类方法

[英]Calling activity class method from FirebaseMessagingService class

How to call activity class method from fcm service. 如何从fcm服务调用活动类方法。

I already tried this way Calling activity class method from Service class 我已经尝试过这种方式从Service类调用活动类方法

but in fcm service onBind method is final so we can not overwrite, so any other way to call activity class method from fcm service. 但是在fcm服务中onBind方法是最终的,所以我们不能覆盖,所以任何其他方式从fcm服务调用活动类方法。

for reference some code how to implement fcm. 供参考一些代码如何实现fcm。

public class FCMListenerService extends FirebaseMessagingService {
 @Override
    public void onMessageReceived(RemoteMessage message) {
   }
}

When my activity is running and fcm notification came then i want to update code? 当我的活动正在运行并且fcm通知出现时,我想更新代码? is there any way to handle this requirement ? 有没有办法处理这个要求?

I think you have to try with BroadcastReceiver. 我想你必须尝试使用​​BroadcastReceiver。 This is how you send a message from your FCMListenerService: 这是您从FCMListenerService发送消息的方式:

  public class FCMListenerService extends FirebaseMessagingService {

        public static final String INTENT_FILTER = "INTENT_FILTER";
         @Override
         public void onMessageReceived(RemoteMessage message) {
              Intent intent = new Intent(INTENT_FILTER);
              sendBroadcast(intent);
         }
  }

And then you can try to catch it this way, using broadcast receiver in your activity: 然后你可以尝试以这种方式捕捉它,在你的活动中使用广播接收器:

private BroadcastReceiver myReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        updateUi();
    }
};

Do not forgot to register / unregister your receiver in onCreate() / onDestroy() method from your activity. 不要忘记在您的活动中使用onCreate()/ onDestroy()方法注册/取消注册您的接收器。

onCreate() 的onCreate()

registerReceiver(myReceiver, new IntentFilter(FCMListenerService.INTENT_FILTER));

onDestroy() 的onDestroy()

unregisterReceiver(myReceiver);

Try this Suppose you want to call method of MainActivity ; 试试这个假设您要调用MainActivity方法; Make static variable Context context and initialise in onCreate() of MainActivity. 在MainActivity的onCreate()中创建static变量Context context和初始化。 and make the method static which you want to call in MainActivity say 并使您想要在MainActivity中调用的方法static

public static void updateUi()
{
// code to update Ui
} 

then call from service like this:- 然后从这样的服务电话: -

((MainActivity)MainActivity.context).updateUi();

Update: if you want to perform in multiple activities then you can this method and handle the logic in this updateUi() method 更新:如果要执行多个活动,则可以使用此方法并处理此updateUi()方法中的逻辑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM