Android Easy Permission Library Example

In this tutorial, we are going to learn how to use android Easy Permission Library in our project to check and request for android version 6 and above run-time permissions.

I wrote a tutorial on default Android 6 Run-time permissions. I will suggest you go through this tutorial to understand how to request runtime user permission in android default way.

Working with android run-time permission can be challenging for beginners android developers especially in situation where you will request for different permissions from users at different times.

You need a way to manage it. This is part of what android Easy Permission Library does. To use Easy Permission library in your android project, your Activity class where you will check for user permission at run-time must override the onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) and this callback method will transfer the results to EasyPermission .onRequestPermissionsResult(…) method.

There are few methods in this library but it is important to emphasize on the following

1. hasPermission(…) – This method checks if the app already has the required permissions. This method can take any number of permissions as its final argument.

2. requestPermissions(…) – This method will request the system permissions and show the rationale string provided if necessary. The request code provided should be unique to this request, and the method can take any number of permissions as its final argument.

If you prefer a straight forward and easy looking code, you can implement the PermissionCallback interface. With this Interface, the onPermissionsGranted(int requestCode, List<String> list) and onPermissionsDenied(int requestCode, List<String> list) methods will be overriden.

You can find more information about this library in its Github repository. There is also a test sample that can help you understand how this library works.

Now is the best time to try and see how we can use the library in our android project. We are going to test it with a simple camera application and in this case we will need to request for READ_EXTERNAL_STORAGE permission from our users at run-time.

The sample app will use camera intent on button click to open default device camera and when a picture is taken, we will like to read to image in external storage and display it on an ImageView inside our app. This is where we need permission.

The app layout file will be simple. Just a Button that will trigger device camera and an ImageView that will be used to display captured image.

Before we start coding, it is important to see what we are planning to achieve in this android tutorial. I have add some screen-shot from the app.

 

APP SCREEN-SHOT

easypermission library

 

CREATE NEW ANDROID PROJECT

Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 10

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 23

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidEasyPermission

Package: com.inducesmile.androideasypermission

Select Empty Activity

Name your activity: MainActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

 

Update AndroidManifest.xml

Since we are going to request for user permission to read from device external storage, we will add a single line of code to our project AndroidManifest.xml file. The updated version is below.

<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.inducesmile.androideasypermission">
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

 

Add Dependency to App Build.Gradle

One way to use external library in android studio project is to add the library in the dependencies section of app level build.gradle. So for the EasyPermission library, we will add the following line to our app level build.gradle file.

compile 'pub.devrel:easypermissions:0.2.0'

Add this line and the you will have a code like below.

apply plugin: 'com.android.application'
android {
    compileSdkVersion 24
    buildToolsVersion "24.0.1"
    defaultConfig {
        applicationId "com.inducesmile.androideasypermission"
        minSdkVersion 16
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile 'junit:junit:4.12'
    compile 'pub.devrel:easypermissions:0.2.0'
}

 

STRINGS.XML

We are going to update our project strings.xml file located in the values folder inside the res folder. Open the file and add the code below to it.

<resources>
    <string name="app_name">Android Easy Permission</string>
    <string name="open_camera">OPEN CAMERA</string>
    <string name="rationale_camera">This app needs access to your camera so you can take pictures.</string>
</resources>

 

COLORS.XML

Open the colors.xml file in the same location as the strings.xml file and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorWhite">#ffffff</color>
</resources>

 

activity_main.xml

As stated earlier, our main layout file will be simple. We will add a Button and ImageView widgets to it. Open the layout file and add the code below to it.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.inducesmile.androideasypermission.MainActivity">
    <Button
        android:text="@string/open_camera"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="24dp"
        android:padding="18dp"
        android:background="@color/colorPrimaryDark"
        android:textColor="@color/colorWhite"
        android:id="@+id/camera_button" />
    <ImageView
        android:id="@+id/camera_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/camera_button"
        android:layout_marginTop="40dp"
        android:contentDescription="@string/app_name"/>
</RelativeLayout>

 

MainActivity.java

In MainActivity class, we will get the instances of our View widgets. The button object is wired with a click event which will trigger the opening of the device camera.

The MainActivity class will also implements the PermissionCallback interface and it will override the onPermissionsGranted(int requestCode, List<String> perms) and onPermissionsDenied(int requestCode, List<String> perms) methods.

When the app wants to read from the device storage, it will prompt the user to accept or denied permission request. User decision is forward to either of the two methods we override.

The complete code for the class is below.

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.util.List;
import pub.devrel.easypermissions.EasyPermissions;
public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks{
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int TAKE_PICTURE = 1;
    private static final int CAMERA_REQUEST_CODE = 100;
    private Bitmap bitmap;
    private Uri capturedImageUri;
    private String selectedImagePath;
    private ImageView photoImage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        photoImage = (ImageView)findViewById(R.id.camera_image);
        Button cameraButton = (Button)findViewById(R.id.camera_button);
        assert cameraButton != null;
        cameraButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, TAKE_PICTURE);
            }
        });
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, MainActivity.this);
    }
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        Log.d(TAG, "Permission has been granted");
        if(capturedImageUri != null){
            selectedImagePath = getRealPathFromURIPath(capturedImageUri, MainActivity.this);
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), capturedImageUri);
                Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, 500, 400, true);
                photoImage.setImageBitmap(resizedBitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        Log.d(TAG, "Permission has been denied");
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && requestCode == 1) {
            String result = data.toURI();
            capturedImageUri = data.getData();
            if(EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)){
                selectedImagePath = getRealPathFromURIPath(capturedImageUri, MainActivity.this);
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), capturedImageUri);
                    Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, 500, 400, true);
                    photoImage.setImageBitmap(resizedBitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else{
                EasyPermissions.requestPermissions(this, getString(R.string.rationale_camera), CAMERA_REQUEST_CODE, Manifest.permission.READ_EXTERNAL_STORAGE);
            }
        }
    }
    private String getRealPathFromURIPath(Uri contentURI, Activity activity) {
        Cursor cursor = activity.getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) {
            return contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            return cursor.getString(idx);
        }
    }
}

This brings us to the end of this tutorial. I hope that you have learn something. Run your app and see for yourself.

You can download the code for this tutorial below. If you are having hard time downloading the tutorial, kindly contact me.

Remember to subscribe with your email address to be among the first to receive my new android blog post once it is published.

OTHER INTERESTING POSTS:

Add a Comment