问题
Have a Firebase Cloud messagin Service running , and i want each time i receive a new message a methode in a specif fragment is called.
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){
}
}
}
回答1:
You can use LocalBroadcastManager
Service:
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);
}
来源:https://stackoverflow.com/questions/60835165/android-call-a-fragment-method-from-a-service