Working with Marshmallow Permissions

0
28

In this tutorial, we will work with Marshmallow Permissions.New versions of Android (equal or above Android M)allows the user to have specific permissions enabled and rest disabled. Therefore not all the permissions will be accepted by default in those Android Versions. So we apply a Version check before executing our code. If the Android Version is equal or above the Marshmallow version then permission has to be granted first, by the user.

In earlier versions, all the permissions were given by the user when he/she chooses to install the application. If the user denies then the app won’t be installed.But now it is possible for the user to disable specific permissions and still install the application. Though it will not obviously work with all features. Here we will create a small project asking the user for the Storage Permissions if the Android Version is equal or above Marshmallow.

Output: –

Download Project – [media-downloader media_id=”1430″]

Download APK – [media-downloader media_id=”1432″]

Wants to Learn Advanced Android Application development from scratch- Beyond Basics

Creating New Project  –

Step 1: – Creating Project – MarshmallowPermissions

Open your Android Studio -> Create a new project -> Choose BlankActivity > Finish

Step 2: Adding Permissions 

Here, we are adding Storage permissions.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mytrendin.marshmallowpermissions">

    <uses-permission android:name="android.permission.WRITE_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>

Step 3: Creating activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:background="#FFFFFF">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="200dp"
        android:src="@drawable/logo" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="This App Checks for Storage Permissions"/>

</LinearLayout>

Step 4: Creating MainActivity.java

Firstly to check the Android Version we will write

 if (Build.VERSION.SDK_INT >= 23) {
            if (checkPermission()) {
              //your Code
            } else {
                requestPermission();
            }
        } else {
            // Code for Below 23 API Oriented Device
        }

Now we will use checkSelfPermission() (this method is called inside our checkPermisson method )to see whether the permission has been granted or not. We will call this when Android Version is found above or equal to Android M. If permission were not granted we will call requestPermission() where we will show prompt user to grant permissions.

Related:

Working with Mutiple Marshmallow Permissions

Android Firebase working with Realtime Database and Storage

Working with TextSwitcher in Android

Working with Android Filterable ListView

Iterators, ListIterators and Enumerations in Collections

When user reacts to that window we will show Toast corresponding to this result

 public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "Permission Granted Successfully! ", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(MainActivity.this, "Permission Denied 🙁 ", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

Your entire MainActivity.java will look like this:

package com.mytrendin.marshmallowpermissions;

import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private static final int PERMISSION_REQUEST_CODE = 1;

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

        if (Build.VERSION.SDK_INT >= 23) {
            if (checkPermission()) {
                // Code for above or equal 23 API Oriented Device
                // Your Permission granted already .Do next code
            } else {
                requestPermission();
            }
        } else {
            // Code for Below 23 API Oriented Device
        }
    }

    private void requestPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Toast.makeText(MainActivity.this, " Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    }

    private boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "Permission Granted Successfully! ", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(MainActivity.this, "Permission Denied 🙁 ", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }
}

If You are Beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

LEAVE A REPLY

Please enter your comment!
Please enter your name here