gpt4 book ai didi

安卓 : Call a Fragment Method from a service

转载 作者:行者123 更新时间:2023-12-04 10:21:18 24 4
gpt4 key购买 nike

运行 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);
}
分段:
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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com