I have an android application that need device current location (latitude and longitude). I've tried some tutorial on the net and specially some solutions from stack overflow, but they doesn't work well for me. My requirement is so simple: First I need it to be fast and need the location once when I the fragment starts. Second I need it to be as precise as possible, I mean it should use GPS first if GPS is not available then use Network provider.
For example, I've tried this solution but it return null after 30 second, but I know there is some all the things is ok because google map and other application works well !!!
Something that almost all the answers suggest is to use getLastKnownLocation(), but I suppose it's not the current and I don't want it if it is so.
can anyone suggest me some kind of simple and fast way to get the location just ONCE ?!
Thanks in advance
AndroidManifest.xml
build.gradle (Module: app)
Set Up Google Play Services
LocationService.kt
your activity
Here, you can use this...
Example usage:
You might want to verify the lat/long are actual values and not 0 or something. If I remember correctly this shouldn't throw an NPE but you might want to verify that.
AndroidManifest.xml:
MainActivity.java:
What you want to do is achieved using the
LocationManager#requestSingleUpdate
. This method attaches a listener in a given looper (if you want or have it) and notifies the location ASAP it is received, only once. The method you suggest is used only as an inexact position before the real one is given to you.In any case it will be fast than milliseconds (unless you are lucky enough to start listening when a location came to the device). Think on the GPS as an element that you enable when waiting for locations and disable when you remove this listening. This behavior is done to avoid draining the user's battery.
So, to sum up: