Search code examples
androidgoogle-mapsbroadcastreceiver

How to access the variable in a BroadcastReceiver to be used in another function (map)?


I have a Broadcastreceiver that works fine and receives data sent via Bluetooth. It splits the data into latitude and longitude values.

The BroadcastReceiver is registered in OnCreate()

BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String text = intent.getStringExtra("theMessage");

            Log.i("text sample", text);

            String coordinates[] = text.split("&");

            btlatitude = Double.parseDouble(coordinates[1]);
            btlongitude = Double.parseDouble(coordinates[0]);

            incomingMessages.setText(text);

            Log.i("text sample lat", String.valueOf(btlatitude));
            Log.i("text sample long", String.valueOf(btlongitude));



            //onMapReady(mMap);


        }
    };

I want to use these btlatitude and btlongitude values to plot a marker in Google Map. I have included a onMapReady(mMap) function in the same activity but the values are always coming 0,0 which is the default value. Please do help me out.

 @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap= googleMap;


        latlng = new LatLng(btlatitude,btlongitude);
        mm=mMap.addMarker(new MarkerOptions().position(latlng).title("My Position"));

        Log.i("text sample lat in bt", String.valueOf(btlatitude));
        Log.i("text sample long in bt", String.valueOf(btlongitude));

    }

Solution

  • You create a method for display marker on google map

    public void showMarker(LatLng latlng){
    
    mMap.addMarker(new MarkerOptions().position(latlng).title("My Position"));
    
    }
    

    and Call it from onReceive

    BroadcastReceiver mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
    
                String text = intent.getStringExtra("theMessage");
    
                Log.i("text sample", text);
    
                String coordinates[] = text.split("&");
    
                btlatitude = Double.parseDouble(coordinates[1]);
                btlongitude = Double.parseDouble(coordinates[0]);
    
                showMarker(new LatLng(btlatitude,btlongitude));
    
            }
        };