Not able to get Location by GPS : Android

拜拜、爱过 提交于 2019-12-25 18:33:31

问题


I am new to android. I am trying to get my location using GPS. I have included the permissions:

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

Whenever I am trying to get my Location from LocationManager using getLastKnownLocation I am getting null object. Also, GPS is enabled. Here is my code:

LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location location;
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
    Log.d("ManualLog", "GPS_DISABLED");
    Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(settingsIntent);
} else {
    Log.d("ManualLog", "GPS_ENABLED");
    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}

回答1:


Are you running it on emulator or device? If on emulator, you may need to send GPS data manually to emulator via "emulator control". In eclipse, you can find it Window>Open Perspective>DDMS.

If you are running on device, is it possible your device never received a GPS signal before?




回答2:


locationManager.getLastKnownLocation will return null if the GPS has not had time to get a fix yet. Android does not provide a 'give me the location now' method. When the GPS has got a fix, the onLocationChanged() will run. It is event driven, you have to be patient and wait for that event. Once onLocationChanged() has run, then getLastKnownLocation() will return a non null value.




回答3:


Try to replace the last line by:

List<String> providers = locationManager.getProviders(true);
if(!providers.isEmpty()) {
    location = locationManager.getLastKnownLocation(providers.get(0));
} else {
   Log.d("ManualLog", "No provider");
}


来源:https://stackoverflow.com/questions/12028117/not-able-to-get-location-by-gps-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!