2

I want to have some code within a android studio application which, will popup a dialog box to request the users permission to enable location on the phone and, to allow the application to access permission. At the moment I have to manually turn on location and, then in the application settings enable location.

I want a popup dialog box to enable this.

This question is now resolved via an answer.

Thanks

Thomas Morris
  • 77
  • 2
  • 10

2 Answers2

4

At first, define your permission in AndroidManifest.xml file

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

Then add those two methods in your activity file.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    checkPermission();

}

public void checkPermission() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            doWhatEveryYouWant :)

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


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

        doWhatEveryYouWant :)

    } else {
        checkPermission();
    }
}
2

Simpily You can use ActivityCompat.requestPermission to show run time permission popup.

An example of code will look like this

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

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

for more information you can follow this link https://stackoverflow.com/a/40142454