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

时间:2016-06-28 12:10:53

标签: java android google-maps android-sharedpreferences

我尝试在服务 A 与片段 B 之间共享值。 我能怎么做?我使用了共享偏好设置功能但没有结果。

这是服务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 )的值<片段 B 强> A 所以我可以在地图上显示我的位置。

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

4 个答案:

答案 0 :(得分:1)

您可以使用Bundle类和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");

答案 1 :(得分:0)

您可以使用:

intent.putExtra()

或者您可以使用

  

SharedPreferences

当你开始这样的新活动时,可以使用

intent.putExtra():

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

答案 2 :(得分:0)

使用Interface或Callback发送数据。活动与活动或活动之间的碎片。

Read here

答案 3 :(得分:0)

活动A中的

  

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

活动B中的

  

Bundle b = getIntent()。getExtras(); double result =   b.getDouble(&#34;键&#34);