Android fused location provider example

Android Location API with the fused location provider — Tutorial

This tutorial describes the usage of the fused location provider.

1. Android Location API

1.1. Determine the current geolocation

Most Android devices allow to determine the current geo location. This can be done via a GPS (Global Positioning System) module, via cell tower triangulation and via wifi networks.

Google Play provides the fused location provider to retrieve the device’s last known location.

1.2. Installation

To use the location manager make the Google play service available via your app build.gradle file.

Also specify the following required permission in your manifest.

1.3. Using the LocationManager

Now you can access the last known location. The fuse location provider provides a new simple API. The following is an example activity which uses it.

1.4. Forward and reverse Geocoding

The Geocoder class allows to determine the geo-coordinates (longitude, laditude) for a given address and possible addresses for given geo-coordinates.

This process is known as forward and reverse geocoding. The Geocoder class uses an online Google service.

1.5. Security

If you want to access the GPS sensor, you need the ACCESS_FINE_LOCATION permission. Otherwise you need the ACCESS_COARSE_LOCATION permission.

1.6. Prompt the user to Enabled GPS

The user can decide if the GPS is enabled or not.

You can find out, if a LocationManager is enabled via the isProviderEnabled() method. If its not enabled you can send the user to the settings via an Intent with the Settings.ACTION_LOCATION_SOURCE_SETTINGS action for the android.provider.Settings class.

Typically you would open an AlarmDialog prompt the user and if he wants to enable GPS or if the application should be canceled.

You cannot enable the GPS directly in your code, the user has to do this.

2. Using GPS and setting the current location

2.1. Activating GPS on the emulator

You need to activate GPS on your test device. If you test on the emulator and its not activated you «null» if you try to use a LocationManager .

The Google Map activity should automatically activate the GPS device in the emulator but if you want to use the location manager directly you need to do this yourself. Currently their seems to be an issue with this.

Start Google Maps on the emulator and request the current geo-position, this will allow you to activate the GPS. Send new GPS coordinates to the Android emulator.

2.2. Setting the geoposition

You can use the «DDMS» Perspective of Eclipse to send your geoposition to the emulator or a connected device. For open this Perspective select Window Open Perspective Other…​ DDMS .

In the Emulator Control part you can enter the geocoordinates and press the Send button.

You can also set the geoposition the Android emulator via telnet. Open a console and connect to your device. The port number of your device can be seen in the title area of your emulator.

Set the position via the following command.

Источник

Android Location Fused Provider

This Android tutorial is to explain what a fused location provider is and how to use it to get the location using a sample Android application. We need not explicitly choose either GPS or Network location Provider, as the “Fused Location Provider” automatically chooses the underlying technology and gives the best location as per the need.

Читайте также:  Изменение частот процессора андроид

In this tutorial we will be using the FusedLocationProviderApi which is the latest API and the best among the available possibilities to get location in Android. If for some reason you wish to use the old APIs then refer the earlier written tutorial to get current location in Android.

Fused Location Provider

  • It provides simple and easy to use APIs.
  • Provides high accuracy over other options.
  • Utilizes low power by choosing the most efficient way to access the location.

Three Use Cases for location access

With respect to fused location provider, we can broadly classify the API usage in three use cases.

  1. getLastLocation(GoogleApiClient) this API should be used when there is no need for continuous access to location from an application. Like one shot access or get user location based on some action. This is the simplified way to get the device location and also may not provide high accuracy.
  2. requestLocationUpdates(GoogleApiClient,LocationRequest, LocationListener) this API should be used when there a need for continuous location updates and the location is accessed when the application is active in foreground.
  3. requestLocationUpdates (GoogleApiClient, LocationRequest, PendingIntent) this API is used to receive location updates in the background even when the application is not active. So the difference is PendingIntent.

Example Android Application to Get Location

Following is an example Android application that shows how to get the current user location. This also continuously updates the location on the move.

Prerequisite

Google Play Services is required. If you are using Android Studio and Gradle, you should have the following dependencies added in build.gradle file

Note: As of now(14 March 2015), Fused location provider API is not working in all the Android Nexus virtual device emulators. Its a widely reported defect. You can use any other AVD to test in the emulator like WVGA AVDs. I used “4 WVGA API 21” virtual device in emulator to test it. It is also working on a real device and I tested it in Panasonic P81.

AndroidManifest.xml

Remember to give access permissions as shown below. You need not give permission for GPS, Network providers. I have seen Android location access tutorial examples giving all the available permission in the world. Just on android.permission.ACCESS_FINE_LOCATION is enough.

ACCESS_COARSE_LOCATION permission is for approximate location access using cell towers and Wi-Fi. ACCESS_FINE_LOCATION is for precise location access using GPS or cell towers and Wi-Fi. Choose the one that is appropriate for you and do not give both. Battery power is used accordingly.

FusedLocationProviderApi Usage

FusedLocationProviderApi

FusedLocationProviderApi can be accessed via LocationServices as below,

GoogleApiClient

FusedLocationProviderApi requires the GoogleApiClient instance to get the Location and it can be obtained as below.

  • Instantiating the GoogleApiClient should be done in onCreate of the application Activity.
  • googleApiClient.connect() should be done in onStart and disconnect() in onStop .
  • When the GoogleApiClient is connected successfully, onConnected(Bundle) callback will be called. There we should register with LocationListener for location updates as LocationServices.FusedLocationApi.requestLocationUpdates(
    mGoogleApiClient, mLocationRequest, this);

Location Interface Implementations for Callbacks

The following interfaces should be implemented to get the location update.

  • LocationListener provides call back for location change through onLocationChanged.
  • GoogleApiClient.ConnectionCallbacks provides call back for GoogleApiClient onConnected.
  • GoogleApiClient.OnConnectionFailedListener provides call back for GoogleApiClient onConnectionFailed.

Continuous Location Access Activity

Following is the complete class which accesses the Fused Location Provider to get the location continuously in the Android example application.

Android Layout File

Test Run the Location Application via Android Emulator

In Eclipse, Open DDMS perspective (Window -> Open Perspective)

  • Select your emulator device
  • Select the tab named emulator control
  • In ‘Location Controls’ panel, ‘Manual’ tab, give the Longitude and Latitude as input and ‘Send’.

In Android Studio, open Android Device Monitor

The below screen shot will help,

Comments on «Android Location Fused Provider»

[…] This tutorial is to learn how to show the current location on map in an Android application using Google Maps API. Previously we have seen tutorials to get the current location using the different location providers. If you are looking to just get the latitude and longitude of a location, the refer get current location using Android Fused location provider tutorial. […]

Читайте также:  Build craft для android

Thank you! I couldn’t find a specific example of grabbing the fused provider anywhere until getting here.

This tutorial is great!
Is there another way to get the location as soon as see the activity on my screen in oppose to clicking a button?
I’ve tried placing the request for location in onCreate, onStart and onResume, but that only works in onResume after I really resume from standby.

Thanks you, this tutorial is so great. Have a nice day!

After implementing it I’m getting no Location at all. I’m not even getting default status icon when some app is trying to get the current location. With previous examples it worked fine.

dependencies <
compile fileTree(dir: ‘libs’, include: [‘*.jar’])
compile ‘com.android.support:appcompat-v7:21.0.3’
compile ‘com.google.android.gms:play-services:6.5.87’
>
And in activity:
if (!isGooglePlayServicesAvailable()) <
finish();
>
setContentView(R.layout.map_layout);

fusedLocationService = new FusedLocationService(this);
tvLocation = (TextView) findViewById(R.id.curPositionText);

Location location = fusedLocationService.getLocation();
String locationResult;
if (null != location) <
Log.i(TAG, location.toString());
double latitude = location.getLatitude();
double longitude = location.getLongitude();
// float accuracy = location.getAccuracy();
// double elapsedTimeSecs = (double) location.getElapsedRealtimeNanos()
// / 1000000000.0;
// String provider = location.getProvider();
// double altitude = location.getAltitude();
locationResult = “Latitude: ” + latitude +
” Longitude: ” + longitude;
> else <
locationResult = “Location Not Available!”;
>
tvLocation.setText(locationResult);

How would I setup pooling so that I can send the onChanged() location from the FusedLocationService back to the View without having to click on the button?

Источник

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:

  1. 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.
  2. 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.
  3. 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).
Читайте также:  Нет звука андроид е53

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.

Источник

Оцените статью