Overview

In this tutorial, we show you how to request contact permission and allows to read contacts on Android 6.0 or higher and older versions of Android.
Follow the steps mentioned below to develop this application.


Android request contact permission Example

Create an Android Project

Open Android Studio and create a new project with an empty activity called MainActivity.java

create new Android request contact permission


create new Android request contact permission
create new Android request contact permission
create new Android request contact permission
create new Android request contact permission

Adding Permissions in AndroidManifest.xml

Go to AndroidManifest.xml and we add manually in the manifest file within manifest tag by
<uses-permission android:name="android.permission.READ_CONTACTS" />
Adding this line will allow the app to access the contacts.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jackrutorial.requestpermissionsreadcontact">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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>

Create an 'Show Contacts' button

Add Button widget to activity_main.xml layout. Change the activity_main.xml layout to the following.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnShowContact"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Contacts"
        />

</android.support.constraint.ConstraintLayout>
And then cast 'Show Contacts' button with Button Class and set ClickListener in MainActivity.java class
public class MainActivity extends AppCompatActivity {

    Button btnShowContacts;

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

        btnShowContacts = (Button) findViewById(R.id.btnShowContact);

        btnShowContacts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    //requestContactPermission
            }
        });
    }
}

Android request contact permission

We define a constant variable is the following
public static final int PERMISSIONS_REQUEST_READ_CONTACTS = 1;
Create the getContacts() method in MainActivity activity code to the following.
private void getContacts() {
    //TODO get contacts code here
    Toast.makeText(this, "Get contacts ....", Toast.LENGTH_LONG).show();
}
This is a demo method for getContacts, we do not write code here.
Create the requestContactPermission() method in MainActivity activity code to the following.
public void requestContactPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    android.Manifest.permission.READ_CONTACTS)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Read Contacts permission");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setMessage("Please enable access to contacts.");
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @TargetApi(Build.VERSION_CODES.M)
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        requestPermissions(
                                new String[]
                                        {android.Manifest.permission.READ_CONTACTS}
                                , PERMISSIONS_REQUEST_READ_CONTACTS);
                    }
                });
                builder.show();
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.READ_CONTACTS},
                        PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            getContacts();
        }
    } else {
        getContacts();
    }
}
In the snippet code above. The Android 6.0 or higher (>= API level 23) have new permissions system. But using the support library makes it easier to provide compatibility with older versions of Android.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
...
} else {
  getContacts();
}
This snippet shows how to check if the activity has permission to read to the contact. We call the ContextCompat.checkSelfPermission() method. If the app has the permission, the method returns PERMISSION_GRANTED else PERMISSION_DENIED.
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
 ...
} else {
 getContacts();
}
If the app does not have permission to read the user's contacts, it should show an explanation for needing the permission then requests the permission.
public void requestContactPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    android.Manifest.permission.READ_CONTACTS)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Read Contacts permission");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setMessage("Please enable access to contacts.");
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @TargetApi(Build.VERSION_CODES.M)
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        requestPermissions(
                                new String[]
                                        {android.Manifest.permission.READ_CONTACTS}
                                , PERMISSIONS_REQUEST_READ_CONTACTS);
                    }
                });
                builder.show();
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.READ_CONTACTS},
                        PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            getContacts();
        }
    } else {
        getContacts();
    }
}

The permissions request response

When the user responds to the app's permission to read the user's contacts request, the system invokes the app's onRequestPermissionsResult() method, passing it the user response.
@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSIONS_REQUEST_READ_CONTACTS: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getContacts();
            } else {
                Toast.makeText(this, "You have disabled a contacts permission", Toast.LENGTH_LONG).show();
            }
            return;
        }
    }
}
Complete MainActivity Code
package com.jackrutorial.requestpermissionsreadcontact;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    public static final int PERMISSIONS_REQUEST_READ_CONTACTS = 1;
    Button btnShowContacts;

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

        btnShowContacts = (Button) findViewById(R.id.btnShowContact);

        btnShowContacts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestContactPermission();
            }
        });
    }

    private void getContacts() {
        //TODO get contacts code here
        Toast.makeText(this, "Get contacts ....", Toast.LENGTH_LONG).show();
    }

    public void requestContactPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        android.Manifest.permission.READ_CONTACTS)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Read Contacts permission");
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setMessage("Please enable access to contacts.");
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @TargetApi(Build.VERSION_CODES.M)
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            requestPermissions(
                                    new String[]
                                            {android.Manifest.permission.READ_CONTACTS}
                                    , PERMISSIONS_REQUEST_READ_CONTACTS);
                        }
                    });
                    builder.show();
                } else {
                    ActivityCompat.requestPermissions(this,
                            new String[]{android.Manifest.permission.READ_CONTACTS},
                            PERMISSIONS_REQUEST_READ_CONTACTS);
                }
            } else {
                getContacts();
            }
        } else {
            getContacts();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSIONS_REQUEST_READ_CONTACTS: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    getContacts();
                } else {
                    Toast.makeText(this, "You have disabled a contacts permission", Toast.LENGTH_LONG).show();
                }
                return;
            }
        }
    }
}

Run this app in the Android Emulator

You can run this app from an Android Studio project. Or you can run this app that's been installed on the emulator as you would run any app on a device. To start the emulator and run this app in your project.
  • Open Android Studio project and click Run.
  • In the Select Deployment Target dialog, select an existing emulator definition, and then click OK.
Note:
  • If you don’t see a definition you want to use, click Create New Virtual Device to launch the AVD Manager. After you define a new AVD, in the Select Deployment Target dialog (Android 6.0 API level 23 or higher), click OK.
  • If you want to use this emulator definition as the default for your project, select Use same selection for future launches. 
Android request contact permission Emulator
Request contact permission Emulator

requests the permission
get contacts
disabled a contacts permission

Previous Post
Next Post

post written by: