【发布时间】:2016-10-16 19:11:38
【问题描述】:
请考虑这段代码:
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 类中,我尝试停止当用户关闭某个设置时位置更新,方法如下:
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。没有位置更新,一切都如预期的那样安静。但是在使用设备移动了几个小时之后,突然之间,我再次开始获取位置更新,例如,IntentService 的onHandleIntent() 中的所有代码都会在位置发生变化时得到忠实执行。
要设置自动模式,用户必须启动应用程序,因此Presence 类肯定会被实例化(单例)并且应用程序中设置的任何内容都会反映到其@987654329 @flag,如果我没记错的话。然而,我怀疑这个标志。
请让我知道我还需要做什么才能立即停止并保持这种状态 em> 直到用户打开设置?我做错了什么或错过了什么?
非常感谢!
【问题讨论】:
-
Intent 服务在完成其任务后会被终止,因此如果您有任何位置管理器,它也会被终止,因此您可能应该为您的位置管理器转移到常规服务
-
谢谢@tyczj,我没有在
IntentService中有任何LocationManager。我非常需要IntentService行为,并且它一切正常,除了位置更新的停止... -
我的意思是,如果你试图在意图服务中获取位置更新,它就不起作用。请澄清您是否尝试这样做,如果不是,您为什么要在意图服务中停止它,而不是在哪里运行位置更新
-
你的代码看起来像这样吗? stackoverflow.com/questions/30141631/… 还有,显示您在代码中请求位置更新的位置......
-
将 Toast 放入
if (pref_auto_mode)案例中进行测试,您需要确保在禁用设置时它永远不会进入那里
标签: android location fusedlocationproviderapi