Android 6 Marshmallow Runtime Permissions Request Example

In this android tutorial, we are going to learn how to implement android 6 Marshmallow runtime permission request example.

In Android version below 6, android permission request(s) are granted by users during android app installation but starting from Android 6 Marshmallow, some permissions that are considered as dangerous permissions are requested during runtime.

Please note that android.permission.INTERNET and android.permission.WRITE_EXTERNAL_STORAGE permission is considered normal permission so you are not required to request user permission at runtime.

When requesting for permission, the user will be prompt with a dialog and asked either to accept or deny the permission. If the user accepts the permission, the app will continue to work as it is intended. But if the user denied the permission, there is the possibility to resend a permission request again with a message on why the permission is need. If the user do not want to accept the permission, you should prepare your app to know how to handle permission denial without crashing.

The list below shows the group of permissions that are considered dangerous permissions from android 6 Marshmallow and above.

Android 6 Marshmallow Runtime Permissions

In order to implement android 6 runtime permission, we are going to create a simple WebView app that loads a website using url provided. The WebView uses a custom WebViewClient so that other links within the websites will open inside the WebView.

We are going to as test the normal and dangerous permissions in android 6 Marshmallow. We will use the android.permission.INTERNET and android.permission.RECORD_AUDIO. Although we will only implement the second permission in our code but it will give us an insight on how permissions are granted or denied in android 6.

Before we dive into more details, it is important for us to understand what we are planning to achieve. Below is the screen-shot of the application we will be creating.

android 6 permission

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 7

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: AndroidMarshMalloeExample

Package: com.inducesmile.androidmarshmallowexample

Select Blank Activity

Name the Activity WebActivity

Keep other default selections

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

Lets start with our project

Go to the res folder, then double click on the values folder and double click on the colors.xml file and add the following lines of codes. This will holder all the colors we will use in this tutorial.

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

Now, head over to the strings.xml file and modify the content with the code below.

<resources>
    <string name="app_name">Android Marshmallow Example</string>
</resources>

We are going to modify our project Manifest.xml. Open this file located in manifests folder, we will add the two permissions we are going to test. Add the code below to your Manifest.xml file.

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

Main Layout File

Now we are going to create the main layout file for our main activity class. The layout file will contain a single WebView widge. Open the layout file location in the res > layout directory and add the codes below to the file.

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.inducesmile.androidmarshmallowexample.WebActivity">
    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

MainActivity Class

In the WebActivity class, we will get the instance of our WeView, enable JavaScript and we will create an inner class that will inherit from the WebViewClient.
To focus on the main point of the tutorial, we are going to request for user permission in runtime to use the android.permission.RECORD_AUDIO. Please not that user of android below Android 6 Marshmallow will not see this runtime permission request.

You can create a permission request with the following code.

if (ContextCompat.checkSelfPermission(WebActivity.this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(WebActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_INTERNET);
}

The result of the permission request is checked in overrided method – onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults).
If the user has granted the request, the app will continue to flow the way it was intended and the user will have access to Audio recording in the app.

Otherwise, if the permission is denied, a new request can be resend to the user and there is an option to enlighten the user while the permission is requested and how important it is for the user to accept the permission.

The code below exemplified this scenario.

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == REQUEST_INTERNET) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //start audio recording or whatever you planned to do
        }else if (grantResults[0] == PackageManager.PERMISSION_DENIED){
            if (ActivityCompat.shouldShowRequestPermissionRationale(WebActivity.this, Manifest.permission.RECORD_AUDIO)) {
                //Show an explanation to the user *asynchronously*
                ActivityCompat.requestPermissions(WebActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_INTERNET);
            }else{
                //Never ask again and handle your app without permission.
            }
        }
    }
}

Now, open the WebActivity.java file in your IDE and add the code below inside this file.

import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebActivity extends AppCompatActivity {
    private static final int REQUEST_INTERNET = 200;
    private WebView htmlWebView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        ActionBar actionBar = getSupportActionBar();
        if(null != actionBar){
            actionBar.hide();
        }
        if (ContextCompat.checkSelfPermission(WebActivity.this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(WebActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_INTERNET);
        }
        htmlWebView = (WebView)findViewById(R.id.webView);
        assert htmlWebView != null;
        WebSettings webSetting = htmlWebView.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setDisplayZoomControls(true);
        htmlWebView.setWebViewClient(new CustomWebViewClient());
        htmlWebView.loadUrl("https://inducesmile.com/blog");
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_INTERNET) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //start audio recording or whatever you planned to do
            }else if (grantResults[0] == PackageManager.PERMISSION_DENIED){
                if (ActivityCompat.shouldShowRequestPermissionRationale(WebActivity.this, Manifest.permission.RECORD_AUDIO)) {
                    //Show an explanation to the user *asynchronously*
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setMessage("This permission is important to record audio.")
                            .setTitle("Important permission required");
                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            ActivityCompat.requestPermissions(WebActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_INTERNET);
                        }
                    });
                    ActivityCompat.requestPermissions(WebActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_INTERNET);
                }else{
                    //Never ask again and handle your app without permission.
                }
            }
        }
    }
    private class CustomWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
}

This brings us to the end of this tutorial. I hope that you have learned something new.

I have a complete Android login source codes with advance features and admin back-end with user login details that comprises of Android Facebook Login, Android Twitter Login, Android Google Plus Login, Android Login and Registration with Php and MySql, Android Login with Firebase. It sells for $3.

Kindly contact me if you need it. I offer 24 – 7 support for smooth integration in your application.

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

Remember to subscribe with your email address so that you will be among the first to receive my new post once it is published.

Please if you love this tutorial, kindly download my android app – Complete Mathematics – in Google Play Store and let me know what you think about it.

OTHER INTERESTING POSTS:

3 Comments

    • Henry

Add a Comment