2

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){


        }




    }

}

Ouaaqil Youssef
  • 79
  • 2
  • 10

1 Answers1

2

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);
}
aiqency
  • 1,015
  • 1
  • 8
  • 22