0
votes

I am trying to activate the location on my device using the pop up in my device without going to the settings page; I tried multiple solutions on stack overflow, but none seems to work on turning my emulator or device location on.
My location code is as follow:

OnRequest:

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull 
String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

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

          permission. its an array becayse it can be multiple permissions


            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0 , 0, locationListener);
        }


    }


}

Main:

  locationManager =  (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);


    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {

            Log.i("location",""+location.toString());
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){

    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION} ,1);


}else{
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0 , 0, locationListener);

}

Manifest:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Build Gradle:

compile 'com.android.support:support-v4:25.0.0'
compile 'com.google.android.gms:play-services-maps:10.2.4'
compile 'com.google.android.gms:play-services-location:10.2.4'
2

2 Answers

0
votes

In your main class Modify this:

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

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION} ,1);
return;
}else{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0 , 0, locationListener);
}
0
votes

1) Remove the code related to run time permission and try running the app on a device having any android version released before Marshmallow. This way you will get to know whether the the issue is related to the run time permission or not

2) You can try this library to implement run time permissions. It is very simple and easy to use. https://github.com/Karumi/Dexter