java Android - 仅获取一次位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4735942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:47:29  来源:igfitidea点击:

Android - Get Location Only One Time

javaandroidlocation

提问by Marco Faion

i need to get the current user location on an android app, so i've read some tutorials and samples on the web, but i see that in all the examples, the location is retrived from a "onLocationChange" that mean that every time the location change, the code in the "onLocationChange" is executed.

我需要在 android 应用程序上获取当前用户位置,所以我在网上阅读了一些教程和示例,但我看到在所有示例中,位置是从“onLocationChange”中检索的,这意味着每次位置改变,执行“onLocationChange”中的代码。

i need only to get the user location at the moment the app is started.

我只需要在应用程序启动时获取用户位置。

Thanks for your help!

谢谢你的帮助!

采纳答案by Eric Levine

You can do this with LocationManager.getLastKnownLocation

您可以使用 LocationManager 执行此操作。获取上次已知位置

回答by Phobos

You can get the last know location using the code below. It gets the location providers and loops over the array backwards. i.e starts with GPS, if no GPS then gets network location. You can call this method whenever you need to get the location.

您可以使用下面的代码获取最后知道的位置。它获取位置提供者并向后遍历数组。即以 GPS 开头,如果没有 GPS,则获取网络位置。您可以在需要获取位置时调用此方法。

private double[] getGPS() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
List<String> providers = lm.getProviders(true);

/* 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;
}

double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}

回答by Tom

Put this in the main activity:

把它放在主要活动中:


boolean bFirst = true;
function void onCreate(blabla) {
  if(bFirst) {
    //Do your stuff to get the location
    bFirst = false;
  }
}

Put the same in the onResume();

将相同的内容放在 onResume() 中;

回答by ChallengeAccepted

For the getGPS()method which Phobos proposed to work properly you have to allow access within your AndroidManifest.xml

对于getGPS()Phobos 建议正常工作的方法,您必须允许在您的 AndroidManifest.xml 中访问

That will get rid of your error of receiving 0.0

这将消除您收到 0.0 的错误

Add these lines:

添加这些行:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.LOCATION_HARDWARE" />