即使启用了 GPS,也无法获取位置
Posted
技术标签:
【中文标题】即使启用了 GPS,也无法获取位置【英文标题】:cannot get location even gps are enabled 【发布时间】:2020-04-01 15:08:07 【问题描述】:我有一个使用多个位置提供程序来获取最新的已知位置信息的功能,但我发现这是不稳定的(至少在我的带有 android 7.1 的小米中,我仍然不知道在另一部手机上),这是我的功能:
private String getGPS()
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(false);
/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location l = null;
for (int i=providers.size()-1; i>=0; i--)
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
String msg = "";
if (l != null)
msg = l.getLatitude() + "|" + l.getLongitude();
return msg;
【问题讨论】:
【参考方案1】:方法getLastKnownLocation()
仅在另一个应用程序最近请求它时才返回有效位置。
你应该这样做:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Avoid the for loop, in this way you can know where there's an issue, if there'll be
Location l = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (l== null)
l = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (l== null)
l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
那么,如果这三个都为null,则意味着没有应用程序在您之前请求位置,因此您必须自己进行请求: 您可以请求“位置更新”,因此您必须实现一个侦听器,如果需要,您可以将其插入到您的活动中,以这种方式:
class YourActivity extends Activity() implements LocationListener
private Location l;
private LocationManager lm;
@Override
... onCreate(...)
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
l = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (l == null)
l = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (l == null)
l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (l == null) //If you need a real-time position, you should request updates even if the first location is not null
//You don't need to use all three of these, check this answer for a complete explanation: https://***.com/questions/6775257/android-location-providers-gps-or-network-provider
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10 * 1000, 10F, this);
lm.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 10 * 1000, 10F, this);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000, 10F, this); //This consumes a lot of battery
//10 * 1000 is the delay (in millis) between two positions update
//10F is the minimum distance (in meters) for which you'll have update
@Override
void onLocationChanged(Location location)
l = location;
private String getGPS()
String msg = "";
if (l != null)
msg = l.getLatitude() + "|" + l.getLongitude();
return msg;
//To avoid crash, you must remove the updates in onDestroy():
@Override
void onDestroy()
lm.removeUpdates(this)
super.onDestroy()
Android 6+ 当然你必须插入应用内权限请求
【讨论】:
谢谢先生的回答,顺便说一句,lm.requestLocationUpdates
最后不会收到这个上下文,我如何在不实现 LocationListener 的情况下使用它
如果不想在Activity中设置,可以声明LocationListener类型的对象,但是没有监听器就不能请求更新
是的,先生,现在我使用requestSingleUpdate
,因为 getGPS() 在 runnable 内部被调用,谢谢先生以上是关于即使启用了 GPS,也无法获取位置的主要内容,如果未能解决你的问题,请参考以下文章