Android Turn on GPS programmatically
Jan 2, 2019 · 3 min read
In our previous article, we have taught you how to get location using FusedLocationProviderClient and we also mentioned in that article that for using this feature, you need to turn on device GPS manually by redirecting to settings of your device.
Programmatically we can turn on GPS in two ways. First, redirect the user to location settings of a device (by code) or another way is to ask to turn on GPS by GPS dialog using LocationSettingsRequest and SettingsClient.
First method:
By usin g this, the user will be redirected to the Settings page of your device and user has to turn on GPS manually.
Second method:
In this method, we will show you code to turn on GPS using android gms location request and setting clients. Here we provide a custom class GpsUtils.java with a code written in it with method turnGPSOn(). The method has a callback listener to check the current status of GPS. If GPS is already turned on, no further code will be determined and callback revert true as GPS is on. Let’s look at the code below and we will show how to use GpsUtils.java.
SettingsClient class is the main key point for interacting with location-based API. This API makes it easy for an app to ensure that the device’s system settings are properly configured for the app’s location needs.
LocationSettingsRequest Specifies the types of location services the client is interested in using. Settings will be checked for optimal functionality of all requested services. Use LocationSettingsRequest.Builder to construct this object.
GPS Dialog will be shown for SettingsClient’s failure callback and it will result in an activity’s onActivityResult(). So basically if the user agrees for turn on GPS, we can enable GPS flag in our activity.
and now call GpsUtils class before getting a location.
We recommend you to put this code in onCreate() of your activity. So that, turn on GPS and getting a location works well one by one. And also GPS takes some minor delay to trace your device location.
We have provided code in the previous article to get a location. Thus, we made changes for GPS in that code and republish the same code.
Find code here. Code contains previous article example for getting the current location.
Источник
Using Fused Location API To Fetch Current Location
After booking an Uber cab, have you noticed the movement of cabs on the roads while coming to your address? There are various applications that use some kind of location services. Using GPS to update the location is a very cool feature. That moving icon of a car(in case of Uber) looks very cool and being an Android developer, we all have thought of using these type of features in our mobile application but ended up with some kind of error while integrating this feature.
So, don’t worry, in this blog we will learn how to use Fused Location API to get the accurate location of your Android device by making use of your phone’s own GPS. We will show the current location of the mobile using the GPS and whenever the location of the phone will be updated then the updated location will be shown on the app. So, let’s get started.
Before moving forward
Before moving forward to the coding part, we need to understand the location permissions.
If you want to get the current location of your user, then you have to add the location permission to your application. Android provides the following location permission:
- ACCESS_COARSE_LOCATION : By adding this in your application, allows you to use WIFI or mobile cell data(or both) to determine the device’s location. The approximation by using this permission is close to the city level.
- ACCESS_FINE_LOCATION : This uses your GPS as well as WIFI and mobile data to get the most precise location as possible. By using this, you will get a precise location of your user.
- ACCESS_BACKGROUND_LOCATION : This permission was introduced in Android 10. So, for Android 10 or higher, if you want to access the user’s location in the background, then along with any of the above two permissions, you need to add the ACCESS_BACKGROUND_LOCATION permission also.
Also, one thing to be noted here is that we are using dangerous permission, so we need to explicitly ask the user to grant permissions. Learn more about permissions from our blog.
So, we are done with the pre-requisite and now we will learn how to get the current location with the help of an example.
Example
In this example, we will use Fused Location API to get the changed location or you may say, get the current location of a user. We will be using LocationRequest that are used to request quality of service for location updates from the FusedLocationProviderApi .
Apart from getting the updated location, the LocationRequest includes various methods for retrieving locations like a pro. Some of the methods are:
- setInterval(long millis): This is used to set the desired interval after which you want to check for a location update. It is in milliseconds.
- setFastestInterval(long millis): This is used to set the fastest interval for a location update. This might be faster than your setInterval(long) in many cases because if other applications on the device are triggering location updates at an interval lesser than your interval then it will use that update.
- setSmallestDisplacement(float smallestDisplacementMeters): This will set the minimum displacement between location updates i.e. the smallest displacement required for a location update. It is in meters and the default value of this is 0.
- setPriority(int priority): This is used to set the priority of location received. It can be PRIORITY_BALANCED_POWER_ACCURACY (for accuracy up to block level) or it can be PRIORITY_HIGH_ACCURACY (to get the most accurate result) or it can be PRIORITY_LOW_POWER (to get the accuracy up to city level) or it can be PRIORITY_NO_POWER (to get the most accurate information without providing some additional power).
Get the full list of available methods from here.
Now, follow the below steps to get your current location using Fused Location Provider:
Create a Project
- Start a new Android Studio Project
- Select Empty Activity and Next
- Name: Fused-Location-API-Example
- Package name: com.mindorks.example.fusedlocation
- Language: Kotlin
- Finish
- Your starting project is ready now
In order to use the Fused Location API, you need to add the dependency of location. So, in your app-level build.gradle file, add the below dependency:
Sync the project.
To use location services, you need to add permission for location in the AndroidManifest.xml file. You can either use ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION , based on your use:
Making layout file
In this project, we will be having two TextViews, one for latitude and one for longitude. The current location of the user will be displayed in these TextViews. So, the code for the activity_main.xml file will be:
Now, we are done with all the dependencies and layout part.
Taking permission from the user
Since we are using a dangerous permission of location, so we need to explicitly ask for permission. Also, before getting the current location of the user, the following cases may arise:
We need to write the function for all these permission checks. So, make a package in the root directory and create an object class in that package.
- Package name: com.mindorks.example.fusedlocation.utils
- Object class name: PermissionUtils
Add the below code in the PermissionUtils.kt file:
Writing code for MainActivity.kt file
Now, in the MainActivity.kt file, override the onStart() method and check if permissions are granted or not using the PermissionUtils class and if the permission is granted and the GPS is enabled in the device, then call the setUpLocationListener() function that is responsible for getting the current location. The following is the code of onStart() :
now, make a function named setUpLocationListener() . In the function, create an instance of the Fused Location Provider client.
Now, we need to define the type of location request that we want i.e. we can set the desired level of accuracy of location, the desired interval of location update, desired priority, etc. All these settings can be done by using the LocationRequest data object. So, we can add the below code:
Now, all we need to do is call the requestLocationUpdates() method and pass the LocationRequest and a LocationCallback. After that, the onLocationResult will be invoked and it contains a list of locations. You can get the latitude and longitude from this location variable and use it as per your choice. Here, we are updating our TextView with this latitude and longitude. So, the final code of setUpLocationListener() will be:
Finally, add the callback for the result from requesting permissions:
Run the application
Run the application on your device and try to verify all the cases of permission and also try to change the location of your device to find if the location is updating on the TextView or not.
Summary
In this blog, we learned how to display the changed location of the user in your app. We have used the Fused Location API for the same purpose.
Источник
Get Current location using FusedLocationProviderClient in Android
Sep 4, 2018 · 4 min read
Hello to coders,
Previously we have taught you how you get current location using GPS/Network Provider. Then android has revealed FusedLocationProviderClient under GoogleApi. FusedLocationProviderClient is for interacting with the location using fused location provider.
( NOTE : To use this feature, GPS must be turned on your device. For manually ask the user to turn on GPS, please check next article)
So let’s get started for the tutorial for getting the current location.
First, add a dependency for location by play services:
Then define FusedLocationProviderClient:
Add permission in manifest.xml
Now ask for runtime permission for above android 6 OS devices
N o w, request for permission if not granted and get the result on onRequestPermissionsResult overridden method, check highlighted code below:
Here, when you allow using permission for an app, it will return to onRequestPermissionsResult method. And again get the last location and print location on textview.
Above code will work if an app has already granted the location permission
Here you can notice, why we put a condition that if(location!=null) before getting latitude-longitude. The location object may be null in the following situations:
- Location is turned off in the device settings. The result could be null even if the last location was previously retrieved because disabling location also clears the cache.
- The device never recorded its location, which could be the case of a new device or a device that has been restored to factory settings.
- Google Play services on the device have restarted, and there is no active Fused Location Provider client that has requested location after the services restarted. To avoid this situation you can create a new client and request location updates yourself.
Now if in case we can’t getting location then we have an option for request location updates. Location updates will give you continuous location at any specific time interval as per your request. Let’s move on location updates.
Here we definitely get the current location using this location updates. And once we get the location, we can also remove location continuous updates else you will get multiple locations updates. This will help you when you want to move the marker on the map as current location changes.
Now you can find some methods of location request like setPriority(), setInterval() and setFastestInterval().
- setPriority: The priority of the request is a strong hint to the LocationClient for which location sources to use. For example, PRIORITY_HIGH_ACCURACY is more likely to use GPS, and is more likely to use WIFI & Cell tower positioning, but it also depends on many other factors (such as which sources are available) and is implementation dependent.
- setInterval: Set the desired interval for active location updates, in milliseconds. The location client will actively try to obtain location updates for your application at this interval, so it has a direct influence on the amount of power used by your application. Choose your interval wisely.
- setFastestInterval: Explicitly set the fastest interval for location updates, in milliseconds. This controls the fastest rate at which your application will receive location updates, which might be faster than setInterval(long) in some situations (for example, if other applications are triggering location updates). This allows your application to passively acquire locations at a rate faster than it actively acquires locations, saving power.
Источник