- How to get user location in Android
- Approach
- How to get current latitude and longitude in android example
- Types of location providers:
- Network Location Provider vs GPS Location Provider
- Steps to get current latitude and longitude in Android
- Location Permissions
- Create LocationManager Instance
- Request Current Location From LocationManager
- Receive Location Update From LocationListener
- Get current location in android example
- Using Location Listener
- Requesting Location Permission
- Getting NetworkingProvider / GpsProvider
- Using Network Provider to get location
- Using GPS provider to get location
- Stop receiving location
- Conclusion
- How to get user current location with GPS or Network in Android?
- How to Get Current Location in Android?
- Taking Location Permission
How to get user location in Android
Many apps in Android uses user’s locations be it for ordering cabs or delivering food and items. Here, a simple android app that would return the user’s latitude and longitude is made. Once the latitude and longitude are known, the exact location on Google Maps can be seen using the following query: https://www.google.com/maps/search/?api=1&query=,
Note: The app will run completely fine on an actual device but might show an error on an emulator. So, please try to run it on an actual device!
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Approach
Step 1. Acquiring Permissions
Since using the user’s permission is a matter concerned with high privacy, first acquire the user’s permission to use their location by requesting them for it. From Android 6.0(Marshmallow), the concept of run-time permissions was rolled in and so the same will be used for getting permission. Any of the following permissions can be used for this:
ACCESS_COARSE_LOCATION: It provides location accuracy within a city block.
ACCESS_FINE_LOCATION: It provides a more accurate location. To do this, it needs to do some heavy lifting so it’s recommended to use this only when we need an accurate location.
In case the app needs to access the user’s location while the app is running in the background, we need to add the following permission along with the above ones:
We need to add all these permissions in the AndroidManifest.xml. To access this file, select your project view as Android and click on:
app->manifests->AndroidManifest.xml.
After adding all the permissions, this is how the AndroidManifest.xml file looks like:
Also, as Google’s PlayServices will be used to access the device’s location, add it in dependencies, in the Build.Gradle (app) file:
Step 2. Designing the layout
As the app is fairly simple, it would contain only the MainActivity and hence a single main layout. In the layout, add an ImageView and two TextViews which would be displaying the user’s latitude and longitude. The latitude and longitude which would be displayed will be returned from the logic of our MainActivity which will be discussed next. Here’s how activity_main.xml looks like:
Output:
Step 3. Writing the logic
- To work on the main logic of our app, we will follow the following key points:
- Check if the permissions we request are enabled.
- Else request the permissions.
- If permissions are accepted and the location is enabled, get the last location of the user.
- In order to get the last location of the user, make use of the Java public class FusedLocationProviderClient. It is actually a location service that combines GPS location and network location to achieve a balance between battery consumption and accuracy. GPS location is used to provide accuracy and network location is used to get location when the user is indoors.
- In conjunction with FusedLocationProviderClient, LocationRequest public class is used to get the last known location. On this LocationRequest object, set a variety of methods such as set the priority of how accurate the location to be or in how many intervals, request of the location is to be made.
- If very high accuracy is required, use PRIORITY_HIGH_ACCURACY as an argument to the setPriority(int) method. For a city level accuracy(low accuracy), use PRIORITY_LOW_POWER.
- Once the LocationRequest object is ready, set it on the FusedLocationProviderClient object to get the final location.
Источник
How to get current latitude and longitude in android example
This Android tutorial is to help learn How to get the current latitude and longitude in the Android platform. Knowing the current location in an android mobile will pave the way for developing many innovative Android apps to solve people’s daily problems. Developing the location-aware application in android needs location providers.
Checkout my other useful post:
Table of Contents
Types of location providers:
GPS Location Provider
Network Location Provider
Any one of the above providers is enough to get the current location of the user or user’s device. But, it is recommended to use both providers as they both have different advantages. Because the GPS provider will take the time to get the location to the indoor area. And, the Network Location Provider will not get location when the network connectivity is poor.
Network Location Provider vs GPS Location Provider
- Network Location provider is comparatively faster than the GPS provider in providing the location coordinates.
- GPS provider may be very very slow in indoor locations and will drain the mobile battery.
- The network location provider depends on the cell tower and will return to our nearest tower location.
- GPS location provider will give our location accurately.
Steps to get current latitude and longitude in Android
- Location permissions for the manifest file for receiving the location update.
- Create LocationManager instance as a reference to the location service.
- Request location from LocationManager.
- Receive location update from LocationListener on change of location.
Location Permissions
To access current location information through location providers, we need to set permissions with the android manifest file.
As higher versions of Android need in-app permission so we will request app permission this way,
ACCESS_COARSE_LOCATION is used when we use network location provider for our Android app.
But, ACCESS_FINE_LOCATION is providing permission for both providers. INTERNET permission is a must for the use of a network provider.
Create LocationManager Instance
For any background Android Service, we need to get a reference for using it. Similarly, location service references will be created using the getSystemService() method. This reference will be added to the newly created LocationManager instance as follows.
Request Current Location From LocationManager
After creating the location service reference, location updates are requested using the requestLocationUpdates() method of LocationManager. For this function, we need to send the type of location provider, number of seconds, distance, and the LocationListener object over which the location to be updated.
Receive Location Update From LocationListener
Receive location update from LocationListener on change of location LocationListener will be notified based on the distance interval specified or the number seconds.
Also, LocationListener having its own callbacks to provide locations based on location/provider changes.
onLocationChanged(Location location) — Called when the location has changed.
onProviderDisabled(String provider) — Called when the provider is disabled by the user.
onProviderEnabled(String provider) — Called when the provider is enabled by the user.
onStatusChanged(String provider, int status, Bundle extras) — This callback will never be invoked on Android Q and above, and providers can be considered as always in the LocationProvider#AVAILABLE state.
Lets see the example for getting current location in android.
Get current location in android example
Using Location Listener
I have created a service that extends locationListener. By extends Location Listener you can receive location updates.
Requesting Location Permission
To get the current latitude and longitude you need a location permission.
Getting NetworkingProvider / GpsProvider
To get the networking / Gps providers, first we need to get location manager.
Once, we get the location manager then we can get the location providers.
check any one of the location provider available to get the location.
Using Network Provider to get location
Once we know that the network provider enabled, Then, you can request the location update from locationLintener using LocationManager.NETWORK_PROVIDER.
In above you can see that, we can also get last known location from the location manager using NETWORK_PROVIDER.
Using GPS provider to get location
Same like Network provider, we can request the location update using LocationManager.GPS_PROVIDER .
Also,we can also get last known location from the location manager using GPS_PROVIDER.
All your location updates received in LocationListener callbacks.
Stop receiving location
To stop receiving location updates in location manager by using removeUpdates.
Entire Android app code is as follows,
GpsTracker.java
MainActivity.java
AndroidManifest.xml
Android Output
Note: If you are running this Android app on the emulator, you need to send the latitude and longitude explicitly for the emulator.
To send the latitude and longitude from your emulator,
- Click More Button from your emulator’s layout.
2. Select Location > Then set the Latitude and Longitude values. Then press Send to set the Latitude and Longitude values to the emulator device.
You can download this example in GITHUB.
Conclusion
Thank you for the reading.
I hope, Now you can able to get the current latitude and longitude in your android device. If you have any issues please put them in the comments section.
Источник
How to get user current location with GPS or Network in Android?
Thanks to smartphones, modern mobile applications can benefit from GPS installed to get user current location. This information adds a lot of value to an application. Web’s giants have understood this since long time.
So, in your next application, you could use GPS or Network to get user current location and add value to your application. For example, if you create a weather application it is essential to know user location to access local weather associated.
To achieve that, there are 2 solutions in Android :
- User SDK standard solution
- Use Location APIs from Google Play Services
In this tutorial, we’re going to learn how to get user location by using SDK standard solution. It can be a better solution because some smartphones haven’t Google Play Services installed. So, combine both solutions can also be a good approach for your application.
First, you need to update your Android Manifest and add ACCESS_FINE_LOCATION permission like this :
In Android standard SDK, you have several providers that can provider you user’s location. Best is obviously GPS but you can get location informations from Network. To be sure to get user’s location, we’re trying to get user location from these both providers. So, you need to add INTERNET permission to your Android Manifest :
Now, you can create location getter class. First, you need to get LocationManager service that is a system service. Instance of LocationManager lets you to check if a particular provider is enabled or no thanks to isProviderEnabled method with provider type in parameter.
If GPS and Network providers are disabled, we stop and return false to indicate to caller that there are no providers enabled on user’s device. Otherwise, we request location updates thanks to method requestLocationUpdates. This method takes a LocationListener instance that will be called when there is an event : location changed, provider disabled, provider enabled or status changed.
To limit user’s location search, we use a GetLastLocation task delayed in 20 seconds. In that task, we stop user’s location search and try to get last known location if there is no result before during request. If there are both results : one from GPS and one from Network, we take the last one.
To let user get user’s location when it’s available, we use a LocationResult abstract class with a gotLocation method that is called when location is found or search is ended.
Our LocationGetter class is like that :
Now, you must call your LocationGetter instance from an activity like that :
Источник
How to Get Current Location in Android?
As a developer when you work on locations in Android then you always have some doubts about selecting the best and efficient approach for your requirement. So in this article, we are going to discuss how to get the user’s current location in Android. There are two ways to get the current location of any Android device:
- Android’s Location Manager API
- Fused Location Provider: Google Play Services Location APIs
Question: Which one is efficient and why?
Answer: Fused Location Provider because it optimizes the device’s use of battery power.
Before moving any of the above methods we will have to take location permission.
Taking Location Permission
Step 1: Define uses permissions for location access in the manifest file
In order to receive location updates from NETWORK_PROVIDER or GPS_PROVIDER, you must request the user’s permission by declaring either the ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission, respectively, in your Android manifest file. Without these permissions, your application will fail at runtime when requesting location updates.
If you are using both NETWORK_PROVIDER and GPS_PROVIDER, then you need to request only the ACCESS_FINE_LOCATION permission, because it includes permission for both providers. Permission for ACCESS_COARSE_LOCATION allows access only to NETWORK_PROVIDER.
Step 2: Define uses permission for internet access because we are going to use Internet Provider.
Step 3: Write a function for checking that location permission is granted or not. If permission is not granted then ask for the permissions in run time.
Источник