0

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?

Shantanu Paul
  • 706
  • 10
  • 26
  • "However, the method throws error if I am not checking for permission granted by the user" -- you may get a warning in the IDE if you are not checking for permissions there. That is merely an IDE warning. So long as you are sure that you are checking for runtime permissions before this, you are fine. – CommonsWare Apr 02 '17 at 18:13

1 Answers1

1

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.

tahsinRupam
  • 6,325
  • 1
  • 18
  • 34