android - 如何将同步服务与onlocation更改为fragment?

标签 android service android-fragments gps

我有一个带有抽屉导航的主要 Activity (白色框架布局)

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;

    }

这里一切都好,在一个 fragment 中有 map ,在另一个 fragment 中有 GPS 和位置的详细信息(海拔、纬度、修复 ecc 的时间)....然后我创建了一项实现位置监听器的服务我希望它将 onlocationchanded 和 gpsstatus 的信息发送到 fragment 1( map 惠特位置)和 2(修复的高度、速度、纬度时间),但我不知道该怎么做......如何同步两个 fragment 的信息? ??谢谢

编辑:

这是我的服务

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;
}

}

这是我的 map fragment :

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



}

}

这是详细信息 fragment :

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)无效更新(){

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

}

}

最佳答案

每次调用 selectItem() 方法时,您都会创建一个新 fragment 。相反,您应该使用方法 findFragmentByTag() 来获取您之前创建的 fragment ,并仅在不存在此类 fragment 时创建新的 fragment 。

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

关于android - 如何将同步服务与onlocation更改为fragment?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17184563/

相关文章:

java - 如果 Activity/UI 空闲一段时间(可能很长),UI 线程会做什么

java - 加载多个 AdMob 视频

Android - 服务和 Activity 交互

c# - 如果登录不正确,如何使 C# WCF session 无效

android - 导航菜单下ScrollView下的Fragment、按钮拉出屏幕

android - fragment isInLayout 返回 false

android - Canvas.getClipBounds 是否分配一个 Rect 对象?

java - 将 SQLite 数据库中的数据显示到自定义 ListView

android - 当应用或服务崩溃时,是否有一些API(或方法)用于获取日志?

android - 切换 fragment 后保留上一个 fragment 的选项菜单