安卓 : Call a Fragment Method from a service

标签 android android-fragments firebase-cloud-messaging android-service

运行 Firebase 云消息服务,我希望每次收到新消息时都会调用特定 fragment 中的方法。

public class FirebaseMsgService extends FirebaseMessagingService {
    public FirebaseMsgService() {
    }


    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        ServiceConnector serviceconnector =null;
        JSONObject data;
        String json = remoteMessage.getData().toString();
        try{
        data= new JSONObject(json);

          **Fragment.method(data);** 

        }
        catch(Exception e){


        }




    }

}

最佳答案

您可以使用LocalBroadcastManager

服务:

private void notifyFragment(String json){
    Intent intent = new Intent("nameOfTheAction");
    Bundle bundle = new Bundle();
    bundle.putString("json", json)); 
    intent.putExtras(bundle);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

fragment :

LocalBroadcastManager bm;

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    bm = LocalBroadcastManager.getInstance(this);
    IntentFilter actionReceiver = new IntentFilter();
    actionReceiver.addAction("nameOfTheAction");
    bm.registerReceiver(onJsonReceived , actionReceiver);
}
 
    
private BroadcastReceiver onJsonReceived = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null) {
            String json = intent.getString("json")
            data = new JSONObject(json);
        }
    }
};
    
@Override
protected void onDetach() {
    super.onDetach();
    bm.unregisterReceiver(onJsonReceived);
}

关于安卓 : Call a Fragment Method from a service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60835165/

相关文章:

android - 无法更改 fragment 错误的标记 - 尝试使用 PagerAdapter 进行切换

node.js - 将 Typescript 转换为 javascript 以实现 Firebase 功能

打开外部 URL 时出现 "startActivityForResult(Intent,int) in Fragment has been deprecated"的 Java 解决方案?

flutter - 如何在通知中显示图像

android - FCM 推送高优先级 topic 自带延迟

java - 尝试做一个公共(public)方法

android - 如何替换 Google 云端硬盘中的文件?

android - Maven Repo 中缺少 "compatibility-v4-r4.jar"

android - 在图库中的 map 被对话框移走后延迟平移

android - 使用单个 Fragment 执行多个 UI 任务?