如何在Android的片段上显示从Firebase Cloud消息接收的数据?

时间:2018-10-19 17:16:09

标签: android firebase firebase-cloud-messaging

这是我的FirebaseMessaging服务,用于接收带有有效负载的消息。我可以成功获取消息。但是如何在另一个片段上使用这些值? 我有一个地图片段,想绘制在地图上收到的坐标。     公共类MyFirebaseMessagingService扩展了FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d("Message Received", "From: " + remoteMessage.getFrom());


    if (remoteMessage.getData().size() > 0) {
        Log.d("datapayload", "Message data payload: " + remoteMessage.getData());


        if (true) {
            // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.

        } else {

        }

    }
    if (remoteMessage.getNotification() != null) {
        Log.d("codefundonotification", "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }


}

}

地图片段:

public class MapFragment extends Fragment implements OnMapReadyCallback {
@Override
public void onMapReady(GoogleMap googleMap){
    map=googleMap;

    LatLng point=new LatLng(12.925471,77.501349);
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(point).title("India");
    map.addMarker(markerOptions);
    map.moveCamera(CameraUpdateFactory.newLatLng(point));
}

1 个答案:

答案 0 :(得分:0)

您必须打开基本活动, 您可以传递一些额外的信息,以告知您的基本活动要打开哪个片段。

Intent mIntent = new Intent(getActivity(), MapActivity.class);
mIntent.putExtra("fragment", "MapFragment");
mIntent.putExtra("data", remoteMessage.getData());

在您的MapActivity中

@Override
protected void onCreate(Bundle savedInstanceState) {

    String fragment = getIntent().getStringExtra("fragment");
    String data = getIntent().getStringExtra("data");

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    if (fragment != null && data!=null && fragment.equals("MapFragment")) {
            Bundle bundle = new Bundle();
            bundle.putString("data", data); //pass data through bundle

            MapFragment mapFragment = new MapFragment();
            mapFragment.setArguments(bundle);

            fragmentTransaction.replace(android.R.id.content, mapFragment);
    } 
    else{ 
         //open another fragment when the activity is not opened from notification
     }
}

在地图片段上检查数据

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            String data = getArguments().getString("data");
        }
    }