2

i have a main activity whit navigation drawer (whit frame layout)

private void selectItem(int position) {

    // Getting reference to the FragmentManager
    FragmentManager fragmentManager  = getSupportFragmentManager();
    FragmentTransaction ft = fragmentManager.beginTransaction();
    switch (position) {

    case 0:
        MapFragment mapFragment= new MapFragment();

        /**
        // Creating a Bundle object
        Bundle data = new Bundle();

        // Setting the index of the currently selected item of mDrawerList
        data.putInt("position", position);

        // Setting the position to the fragment
        mapFragment.setArguments(data);


        // Creating a fragment transaction
        ft = fragmentManager.beginTransaction();
        */

        // Adding a fragment to the fragment transaction
        ft.replace(R.id.content_frame, mapFragment);
        ft.commit();
        break;
    case 1:
        GpsDatiFragment gpsFragment= new GpsDatiFragment();
        ft.replace(R.id.content_frame,gpsFragment);
        ft.commit();
        break;
    case 2:
        AltroFragment altroFragment= new AltroFragment();
        ft.replace(R.id.content_frame, altroFragment);
        ft.commit();
        break;
    case 3: 
        finish();
    default:
        break;

    }

here all ok, In One fragment there is the map and in another there is a details of gps and location (altitude, latitude, time to fix ecc)....then i have create a service that implement location listener and i'll want that it send info of onlocationchanded and gpsstatus to fragment 1 (map whit location) and 2 (altitude speed latitude time to fix) but i dont know how to do.....how sync the info for both fragment??? thanks

edit:

this is my service

public class GPSTracker extends Service implements LocationListener {

private final Context mContext;
String provider;
Criteria criteria;


// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 400; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        //locationManager.addGpsStatusListener(this);
        //Criteria criteria= new Criteria();
        //criteria.setAccuracy(Criteria.ACCURACY_FINE);
        //provider= locationManager.getBestProvider(criteria, false);
        //location= locationManager.getLastKnownLocation(provider);
        //locationManager.requestLocationUpdates(provider, 400, 1, this);

        if (isGPSEnabled){
        if (location == null) {
            locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    MIN_TIME_BW_UPDATES,
                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            Log.d("GPS Enabled", "GPS Enabled");
            if (locationManager != null) {
                location = locationManager
                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);

            }
        }else{
            locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    MIN_TIME_BW_UPDATES,
                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
        }

        }else if (isNetworkEnabled) {
            locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER,
                    MIN_TIME_BW_UPDATES,
                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            Log.d("Network", "Network");
            if (locationManager != null) {
                location = locationManager
                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            }

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

    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }       
}

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
/*
public boolean canGetLocation() {
    return this.canGetLocation;
}*/

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
    //getLocation();
}

@Override
public void onProviderDisabled(String provider) {
    getLocation();
    //locationManager.requestLocationUpdates(locationManager.NETWORK_PROVIDER, 400, 1, this);
}

@Override
public void onProviderEnabled(String provider) {
    getLocation();
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}

and this is my fragment for map:

public class MapFragment extends SupportMapFragment  {

GoogleMap mapView;
Intent intent;

// GPSTracker class
GPSTracker gps;
Location location ;


@Override
public void onCreate(Bundle arg0) {
    super.onCreate(arg0);
    // create class object
    getActivity().startService(new Intent(getActivity(), GPSTracker.class)); 

}

@Override
public View onCreateView(LayoutInflater mInflater, ViewGroup arg1,
        Bundle arg2) {
    return super.onCreateView(mInflater, arg1, arg2);
}

@Override
public void onInflate(Activity arg0, AttributeSet arg1, Bundle arg2) {
    super.onInflate(arg0, arg1, arg2);
}


@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);    

    gps = new GPSTracker(getActivity());

    // check if GPS enabled     
        //location = gps.getLocation();     
        double latitude = gps.getLatitude();
        double longitude = gps.getLongitude();

        mapView = getMap();
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.draggable(true);
        markerOptions.position(new LatLng(latitude, longitude));
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker());
        mapView.addMarker(markerOptions);

        // \n is for new line
        Context context = getActivity().getApplicationContext();
        Toast.makeText(context, "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();    

        // can't get location
        // GPS or Network is not enabled
        // Ask user to enable GPS/network in settings
        // gps.showSettingsAlert();



}

}

this is fragment for deatils:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.activity_main, container, false);



    longitudeField= (TextView) rootView.findViewById(R.id.textView4);
    altitudine= (TextView) rootView.findViewById(R.id.textView6);
    precisione= (TextView) rootView.findViewById(R.id.textView8);
    speed= (TextView) rootView.findViewById(R.id.textView10);
    timeFix= (TextView) rootView.findViewById(R.id.textView12);
    satFixed= (TextView) rootView.findViewById(R.id.textView14);
    elencoSat= (TextView) rootView.findViewById(R.id.textView15);
    latitudeField= (TextView) rootView.findViewById(R.id.textView2);


    gps= new GPSTracker(getActivity());
            update();
       return rootView;
}

/* Request updates at startup */
@Override
public void onResume() {
    super.onResume();
    //update();
    //locationManager.requestLocationUpdates(provider, 400, 1, this);
}

public void update(){

location = gps.getLocation();
lat= location.getLatitude();
lng= location.getLongitude();
pre= (int) location.getAccuracy();
vel= location.getSpeed();
latitudeField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
//altitudine.setText(String.valueOf(alt)+" metri");
precisione.setText(String.valueOf(pre)+" metri");
speed.setText(String.valueOf(vel)+" km/h");

}

}

4

1 回答 1

2

每次selectItem()调用方法时,您都在创建一个新片段。而不是这样做,您应该使用方法findFragmentByTag()来获取您之前创建的片段,并且只有在没有这样的片段时才创建新的片段。

然后,您可以简单地将每个片段的变量存储在您的活动中,并将所需的信息传递给选定的片段。

于 2013-06-19T06:53:46.277 回答