【发布时间】:2017-08-29 03:32:28
【问题描述】:
我在使用 android 时遇到问题,即使用户打开了他们的位置服务,LocationManager 仍然无法找到用户的位置。
在启动需要使用用户位置的活动之前,我会调用以下代码:
//Menu Activity
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER){
Intent nearby = new Intent(mActivityContext, NearbyActivity.class);
startActivity(nearby);
}else{
alertNoGps();
}
打开 GPS 后,可以启动附近的活动,但 LocationManager 仍然无法找到用户最后一个已知位置。我的相关代码是:
//Nearby Activity
try{
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
...
}else{
Toast.makeText ...
}
} catch(SecurityException e){
e.printStackTrace();
}
我目前正在测试的手机运行的是 Android Marshmallow 6.0.1。如果在应用程序通过 android studio 运行之前 GPS 已经打开,那么我可以毫无问题地获取最后一个已知位置。只有在我运行应用程序之前关闭 GPS 并在应用程序运行时打开它时才会出现问题。 LocationManger 是怎么回事?
编辑:在清单中,我同时拥有精细和粗略的位置权限。由于需要额外的权限检查,我不知道这是否是 API 23 及更高版本的问题,但我不得不想象它们仍然由安全异常处理。
【问题讨论】:
-
第三行代码
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){缺少右括号
标签: android geolocation gps android-location locationmanager