如何在 Android 中的服务和片段之间共享值?

How can I share values between a Service and Fragment in Android?

我正在尝试在服务 A 与片段 B 之间共享值。 我能怎么做?我使用了函数 Shared Preferences 但没有结果。

这是服务 A:

public class GPSManager extends Service implements LocationListener {

public Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
Location location;
double latitude;
double longitude;
double myLat;
double myLong;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 60000;
protected LocationManager locationManager;

SharedPreferences sharedPreferences_LAT_LONG = getApplicationContext().getSharedPreferences("Pref.PREFS_LAT_LONG", 0);

public Location getLocation() {
    try {
        locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (isNetworkEnabled)
        {
            getGeoData(LocationManager.NETWORK_PROVIDER);
        }
        else if (isGPSEnabled && location == null)
        {
            getGeoData(LocationManager.GPS_PROVIDER);
        }
        else
        {
            //no gps and network
        }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    return location;
}

private void getGeoData(String provider)
{
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    locationManager.requestLocationUpdates(provider, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
    if (locationManager != null)
    {
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null)
        {
            latitude = location.getLatitude();
            myLat = latitude;
            longitude = location.getLongitude();
            myLong = longitude;

            /*SharedPreferences.Editor editor_LAT_LONG = sharedPreferences_LAT_LONG.edit();
            editor_LAT_LONG.putFloat(String.valueOf(myLat), 0);
            editor_LAT_LONG.putFloat(String.valueOf(myLong), 0);
            editor_LAT_LONG.apply();*/

        }
    }
}

这是片段B:

public class MapFragment extends Fragment {

MapView mapView;

private GoogleMap mMap;

//LatLng Fabrinao_ViaBalbo = new LatLng(43.334546, 12.903811);
LatLng Fabriano_ViaTerenzioMamiani = new LatLng(43.3355506, 12.9024512);

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.map, container, false);

    mapView = (MapView) rootView.findViewById(R.id.mapView);
    mapView.onCreate(savedInstanceState);

    mapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap googleMap) {
            Log.i("DEBUG", "onMapReady");
            mMap = googleMap;
            //mMap.setMyLocationEnabled(true);
            mMap.getUiSettings().setMapToolbarEnabled(false); //Toolbar Disattivata

            /*mMap.addMarker(new MarkerOptions()
                    .position(My_Posizione)
                    .title("Wow!")
                    .snippet("Io sono qui"));*/

            mMap.addMarker(new MarkerOptions()
                    .position(Fabriano_ViaTerenzioMamiani)
                    .title("Fabriano - Via Terenzio Mamiani")
                    .snippet("Hello!")
                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_logomarker)));

            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Fabrinao_ViaBalbo, 15));
            //mMap.setMyLocationEnabled(true);
        }
    });

    return rootView;
}


@Override
public void onResume() {
    mapView.onResume();
    super.onResume();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mapView.onDestroy();
}

我想保存 纬度(myLat) 和 经度(myLong) 从服务 A 到片段 B 这样我就可以在地图上显示我的位置。

谢谢大家,抱歉我的英语不好。

您可以使用:

intent.putExtra()

或者您可以使用

SharedPreferences

intent.putExtra() 可以在您开始新的 activity 时使用,如下所示:

Intent intent = new Intent(activityOne, activityTwo);
intent.putExtra("TAG",VALUE);
startActivity(intent);

这里的 VALUE 可以是 String、int、Bundle.... 阅读更多相关信息 here

并且您可以使用以下方法在新意图中检索此值:

getIntent().getStringExtra(); // if your data was a String

使用接口或回调发送数据。在 Activity 到 Activity 或 Activity 到 Fragment 之间。

Read here

在Activity一个

Intent yourInent = new Intent(thisActivity.this, nextActivity.class); Bundle b = new Bundle(); b.putDouble("key", doubleVal); yourIntent.putExtras(b); startActivity(yourIntent);

在activity乙

Bundle b = getIntent().getExtras(); double result = b.getDouble("key");

您可以使用 Bundle class 和 put_extra 数据来检索和放置。

示例:put_extra

Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);

读取数据

Bundle b = new Bundle();
b = getIntent().getExtras();
Object myParcelableObject = b.getString("name_of_extra");