Search code examples
androidandroid-6.0-marshmallowandroid-permissionsgoogle-location-services

How to integrate Google Location API with android Marshmallow runtime permissions system?


I am trying to get the user's location in my Activity using Google Location API. I have a button, on which if user taps, the location of the user should be retrieved and sent to the app backend. As per Google's documentation, the

LocationServices.FusedLocationApi
                        .getLastLocation(apiClient)

method has to be called in onConnected method. However, the method throws error if I am not checking for permission granted by the user.

My problem is I am asking for permission in onClick method of my button.

I tried putting

LocationServices.FusedLocationApi
                        .getLastLocation(apiClient)

inside the onClick method but it returns a null object.

Is there a proper way to ask location permission from user on tap of a button and not in onCreate method of the activity and still be able to get the location of the user?


Solution

  • I assume you are calling :

    mGoogleApiClient.connect();
    

    in onStart(). Which calls the onConnected() method when the activity starts. You can call it on Button Click after asking run-time permission for Location. Then you will be able to getLastLocation() in onConnected() and you won't face permission error.

    button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                       if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)){
                            mGoogleApiClient.connect();
                        }
                        else{
                            // ask run-time permission
                        }
                    }
                }
            });
    

    Hope this helps.