简体   繁体   English

无法在Android移动设备上获取位置

[英]Fails to get the location on Android mobile

Actually my problem is sometimes i can get the location and sometimes i can't get the location on Android real device. 其实我的问题是有时我可以获取位置,有时我无法在Android真实设备上获取位置。 I used following code for getting the location, 我使用以下代码获取位置,

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);

I need to get the location when my application starts up. 我的应用程序启动时,我需要获取位置。 I don't know why sometimes it fails. 我不知道为什么有时会失败。 How to resolve this issue? 如何解决这个问题?

@jsmith commented on my quesion, @jsmith评论了我的问题,

Increase your power requirements and make sure you test where you can get a network or gps signal. 提高您的电源要求,并确保您测试可以在哪里获得网络或gps信号。 If that helps, then it's simply a case of the sensors not getting enough reception to know the location. 如果这有帮助,那就只是传感器没有得到足够的接收来知道位置的情况。

This is the right answer for my question. 这是我的问题的正确答案。 Now its working fine. 现在工作正常。

You forgot to request for 'Location Updates', use this function after declaring the LocationManager : 您忘记了请求“位置更新”,请在声明LocationManager后使用此功能:

locationManager.requestLocationUpdates(provider, 0, 0, this);

and you have to let the class implements LocationListener then add this function: 并且您必须让该类实现LocationListener然后添加以下功能:

public void onLocationChanged(Location location) {
//get the location here
}

If you don't want to get the location repeatedly, after you get the location you have to stop the 'Location Updates' this way: 如果您不想重复获取位置,则在获取位置之后,您必须通过以下方式停止“位置更新”:

locationManager.removeUpdates(this);

in case you want the application always listen for the 'Location Updates', you better request for updates in onResume() and remove the updates in onPause() & onDestroy() 如果您希望应用程序始终侦听“位置更新”,则最好在onResume()请求更新,并在onPause()onDestroy()删除更新

Good Luck 祝好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM