gpt4 book ai didi

android - 即使启用了 gps 也无法获取位置

转载 作者:行者123 更新时间:2023-11-29 22:38:55 25 4
gpt4 key购买 nike

我有一个使用多个位置提供程序来获取最新已知位置信息的功能,但我发现这是不稳定的(至少在我的 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;
}

最佳答案

方法 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,说明在你之前没有app请求过location,所以你要自己去请求:你可以请求“位置更新”,所以你必须实现一个监听器,如果你愿意,你可以将它插入到你的 Activity 中,这样:

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://stackoverflow.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+,您必须插入应用内权限请求

关于android - 即使启用了 gps 也无法获取位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59233192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com