正确停止位置更新,故障安全

Stopping location updates correctly, failure-safe

请考虑这段代码:

public class Presence implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener
{
          :
          :
    boolean pref_auto_mode;
          :
          :
    private Presence(Context context)
    {
        this.context = context;
        getAppSettings();

        gApiClient = new GoogleApiClient.Builder(context, this, this)
                .addApi(LocationServices.API)
                .build();
        createLocationRequest();
        if (!gApiClient.isConnecting() && !gApiClient.isConnected())
        {
            gApiClient.connect();
        }
    } // of constructor

    @Override
    public void onConnected(Bundle connectionHint)
    {
        Log.e(LOG_TAG, "In onConnected(), gApiClient.isConnected(): " + gApiClient.isConnected());
        createLocationRequest();
        getLocation();
        getSubLocality();

        if (pref_auto_mode)
            startLocationUpdates();
    } // of onConnected()
          :
          :
    private void getAppSettings()
    {
        // Get the user's preferences
        APP_USER_SETTINGS =     PreferenceManager.getDefaultSharedPreferences(context);

                :        
                :        
        pref_auto_mode = APP_USER_SETTINGS.getBoolean(Contract.PREF_AUTO_MODE, false);
                :        
    } // of getAppSettings()

} // of class Presence

这是按预期工作的。

在上面的 Presence class 中,我试图 停止 当用户关闭某个设置时位置更新,如下所示方法:

public void stopLocationUpdates()
{
    if (gApiClient.isConnected())
    {
        LocationServices.FusedLocationApi.removeLocationUpdates(gApiClient, pendingIntent);
        LocationServices.FusedLocationApi.removeLocationUpdates(gApiClient, this);

        Log.e(LOG_TAG, "Location tracker stopped successfully.");

        requestingLocationUpdates = false;
    }
}

我确实看到了 Toast。没有位置更新,一切都像预期的那样安静。但是在使用设备移动几个小时后,突然之间,我又开始获取位置更新,例如,IntentServiceonHandleIntent() 中的所有代码都会在出现时忠实地执行位置更改。

要设置自动模式,用户必须启动应用程序,因此Presence class肯定会被实例化(单例)等等如果我没记错的话,应用程序中的设置会反映在其 pref_auto_mode 标志上。然而,我怀疑这个标志。

请告诉我我还需要做些什么才能使位置更新立即突然停止并且保持这种状态直到用户打开设置?我做错了什么或遗漏了什么吗?

非常感谢!

感谢所有审阅代码并提供宝贵意见的人。

我不得不创建另一个 boolean 字段变量 stopLocationTrackerRequired 并将其设置在 onSharedPreferenceChanged() 覆盖中。只有设置了这个标志,才会调用Presenceclass的stopLocationUpdates(),并且肯定 关闭位置更新。

为了完整性,:

  • Kindly let me know what else I need to do to bring the location updates to a grinding halt instantly and keep it that way till the user switches the setting ON?
  • Am I doing something wrong or missing something?
  • stopLocationUpdates() 正在做实现功能所需的一切。
  • 真的很想知道,但是缺乏如上所示的更多控制