Home Tutorials Hints & Tips

Android FusedLocationProviderAPI Deprecated - How to use the FusedLocationProviderClient - Part 3

This series of tutorials shows you how to use the FusedLocationProviderClient in place of the deprecated FusedLocationProviderAPI to receive location updates to your Android device. This tutorial is written in Java and a Kotlin version will be available soon.


In part 2 we created Java members and associated them with the views in the layout. In this part we go on to look at how the last known location of the device can be recalled and the User Interface updated with that location. We will also go onto the handle the runtime permissions.


First, we need to code a java member to create an instance of the FusedLocationProviderClient Class:


private FusedLocationProviderClient fusedLocationProviderClient;


In the onCreate method, just after the onClickListeners for the ToggleButtons, we need to associate the member with the getFusedLocationProviderClient method in the LocationServices Class.


fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);


We need to set up an onSuccessListener after requesting the last location of the device. Essentially, we will update the User Interface if we successfully get the last known location. There are other similar listeners such as the onFailureListener and we can use that to execute some code in the event we fail to get the last known location of the device. However, in this tutorial we will use only the onSuccessListener.


fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {

   @Override

   public void onSuccess(Location location) {

      //update UI here

});


This will require a runtime permissions check if we are compiling against Android API 23 or higher. API 23 is Marshmallow or Android 6.0. Granting runtime permissions is covered later.


Within the onSuccess method, you need to add code to update the User Interface, first checking that the location is not null.


if (location != null) {

   latitude.setText(String.valueOf(location.getLatitude()));

   longitude.setText(String.valueOf(location.getLongitude()));

   accuracy.setText(String.valueOf(location.getAccuracy()));

   if (location.hasAltitude()) {

      altitude.setText(String.valueOf(location.getAltitude()));

   } else {

      altitude.setText("No altitude available");

   }

   if (location.hasSpeed()) {

      speed.setText(String.valueOf(location.getSpeed()) + "m/s");

   } else {

      speed.setText("No speed available");

   }

}


Some sensors are not able to return an altitude or speed, so it is best to check that the location has these entities by using the hasSpeed and hasAltitude methods.


Next, we need to handle the permissions check. We need to check whether the permission to use the fine location has been granted. If it has, we need not do anything more and we can retrieve the last known location of the device. Otherwise, we must prompt the user to grant permission. If they deny permission, we will simply close the app.


First create an integer constant to represent the requestCode. There is a common callback method to handle all permissions and so we need to identify which permission is being passed to the onRequestPermissionsResult method. The value of the integer is nominal and I chose 101.


Enter the following code to check if the permission to use the fine location has been granted:


if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

  // place all code to get the last know location here along with   onSuccessListener code

} else {

     //request permission

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {      requestPermissions(new      String[]{Manifest.permission.ACCESS_FINE_LOCATION},      MY_PERMISSION_REQUEST_FINE_LOCATION);

  }

}


You will notice a API check surrounding the requestPermissions method. This is needed as the app may support a minimum release below API 23. The requestPermissions method prompts the user to allow or deny permission.


The final task is to complete the callback method to take action based on the user response.


@Override

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

   super.onRequestPermissionsResult(requestCode, permissions, grantResults);


    switch (requestCode) {

       case MY_PERMISSION_REQUEST_FINE_LOCATION:


          if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

             //permission was granted do nothing and carry on

          } else {

             Toast.makeText(getApplicationContext(), "This app requires location              permissions to be granted", Toast.LENGTH_SHORT).show();

             finish();

          }

        break;

     }

}


If the user grants permission we do not need to do anything, simply carry on. If the user denies permission, we will close the app. I used a switch and case as there may be a need to add code to handle more permissions in the future, so we need a case for each requestCode.  


The app is ready to test. The screenshot below shows that the last known location was found, and the data displayed in the User Interface.

In part 4 for we will learn how to turn on location updates.


Android getLastLocation screenshot


After this tutorial your MainActivity.java should look like the one below:






Download Download project files

Privacy and Cookies Disclaimer Copyright
© 2015 - 2018 North Border Tech Training All rights reserved