如何访问 BroadcastReceiver 中的变量以用于另一个函数(地图)?

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

我有一个 Broadcastreceiver 可以正常工作并接收通过蓝牙发送的数据。它将数据拆分为纬度和经度值。

广播接收器在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);


        }
    };

我想使用这些 btlatitude 和 btlongitude 值在 Google 地图中绘制标记。我在同一个 activity 中包含了一个 onMapReady(mMap) 函数,但值始终为 0,0,这是默认值。请帮帮我。

 @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));

    }

您创建了一种在 google 地图

上显示标记的方法
public void showMarker(LatLng latlng){

mMap.addMarker(new MarkerOptions().position(latlng).title("My Position"));

}

并从 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));

        }
    };