Skip to content

Runtime Permissions

Ruben Gees edited this page Sep 17, 2015 · 3 revisions

Guide for implementing requests of Runtime Permissions

Runtime Permissions example

We will be using the OnSlideChangedListener for this. Add it to the IntroductionBuilder like the following:

new IntroductionBuilder(this).withSlides(generateSlides())
                .withOnSlideChangedListener(new IntroductionConfiguration.OnSlideChangedListener() {
                    @Override
                    public void onSlideChanged(int from, int to) {
                        //We need to implement this.
                    }
                }).introduceMyself();

In this sample we will assume that the first Slide asks the user for a Permission. The Permission we will request is WRITE_EXTERNAL_STORAGE. You need to add it to the manifest first:

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

Now we will have a look at the implementation of the OnSlideChangedListener:

@Override
public void onSlideChanged(int from, int to) {
    if (from == 0 && to == 1) { //Check if the user changed from the Slide asking for the Permission to the next.
        if (ActivityCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                              new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
                              12); //12 is a defined identifier by you, which will be used later
        }
    }
}

You might want to check if the permission was granted. You can do that like this:

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

    if (requestCode == 12) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //Permission was granted!
        }else{
            //Permission was not granted.
        }

        //Check other permissions
    }
}

Note: You must build your project with at least sdk 23.