应用程序打开时使用LocationListener[Android]

应用程序打开时使用LocationListener[Android],android,gps,Android,Gps,我正在开发我的第一个应用程序,这个应用程序有两个活动:主活动和第二个活动。这两个活动都需要知道用户位置,因此我创建了一个类似这样的类(我编辑了一个“internet”类): 在主活动中,我基于onCreate事件上的GPSTracker创建一个对象,然后在onStop事件上使用stopUsingGPS()在用户关闭应用程序时停止GPS,并在onResume事件上启动StartSingGPS()以重新启动GPS使用 我的问题是,我还需要在第二个活动中使用GPSTracker,但当第二个活动打开时,

我正在开发我的第一个应用程序,这个应用程序有两个活动:主活动和第二个活动。这两个活动都需要知道用户位置,因此我创建了一个类似这样的类(我编辑了一个“internet”类):

在主活动中,我基于onCreate事件上的GPSTracker创建一个对象,然后在onStop事件上使用stopUsingGPS()在用户关闭应用程序时停止GPS,并在onResume事件上启动StartSingGPS()以重新启动GPS使用

我的问题是,我还需要在第二个活动中使用GPSTracker,但当第二个活动打开时,我的代码会停止GPS(当第二个活动打开时,也会调用onStop事件,而不仅仅是当用户退出应用程序时)

我认为我的方法是错误的

如何创建GPSTracker对象并执行此操作: -仅当用户退出应用程序时停止GPS使用; -在我需要的所有活动中使用它


此外,我想从“活动”触发坐标更改,但我不知道该怎么做?

您需要在MainActivity的onDestroy中调用stopUsingGPS()。所以当用户完全退出你的应用程序时,只有GPS跟踪才会停止。每次活动暂停时,都会调用onStop。因此,在主活动的onDestroy中调用stopUsingGPS()方法。

我刚刚尝试过,但当用户关闭应用程序时,onDestroy并不总是被调用。你可以在这个网站上找到很多关于它的问题。onDestroy将根据每个活动而不是应用程序库被调用。当用户按下某个活动上的“后退”按钮时,将调用该特定活动的onDestroy。我认为最好的解决方案是使用本教程中的IBinder类:
public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

boolean GPSForce = false;

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

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

protected LocationManager locationManager;

public GPSTracker(Context context, Boolean forcegps) {
    this.mContext = context;
    this.GPSForce = forcegps;
    getLocation();
}

public Location getLocation() {
...
}

public void startUsingGPS(){
    getLocation();
}

public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }

    canGetLocation = false;
}

public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    return latitude;
}

public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    return longitude;
}

public boolean canGetLocation() {
    return this.canGetLocation;
}

public void showSettingsAlert(){
...
}

@Override
public void onLocationChanged(Location location) {
    if (location != null) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
    }
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

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

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