Android Runtime Permissions | How to Request permissions in Android Application?

What are Android Runtime Permissions?

Android introduce new feature called as android runtime permission. The purpose of a permission is to protect the privacy of an Android user. Android apps must request permission to access sensitive user data (such as contacts and SMS), as well as certain system features (such as camera and internet). Depending on the feature, the system might grant the permission automatically or might prompt the user to approve the request.

Runtime requests (Android 6.0 and higher)

If the device is running Android 6.0 (API level 23) or higher, and the app's targetSdkVersion is 23 or higher, the user isn't notified of any app permissions at install time. Your app must ask the user to grant the dangerous permissions at runtime.


The user can revoke the permissions at any time, by going to the app's Settings screen. 

System permissions are divided into two categories, normal and dangerous:

  • Normal permissions do not directly risk the user's privacy. If your app lists a normal permission in its manifest, the system grants the permission automatically.
  • Dangerous permissions can give the app access to the user's confidential data. If your app lists a normal permission in its manifest, the system grants the permission automatically. If you list a dangerous permission, the user has to explicitly give approval to your app.

Below are the lists all the current dangerous permissions and their respective groups.


Now we will create android project step by step:

1. Create android project  File => New Project, give application name as RunTimePermission_Demo and compainy domain as example.com & click Next => Next(select any version) => Next(Select Empty Activity) => Finish.

2. Open build.gradle (app level) and make sure that you have set minSdkVersion and targetSdkVersion as we have to support the permissions model in lower versions also. I am keeping minSdkVersion to 16 and targetSdkVersion to 30.

compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.dreamappsstore.valentineday"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
3. In android manifest, first permission android.permission.INTERNET is a normal permission and other two android.permission.READ_CONTACTS, android.permission.WRITE_EXTERNAL_STORAGE are dangerous permissions. Therefore in the following example, we would request the user to grant the later two Android permissions at runtime.

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

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

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

4. Now we will implement two method checkPermission() and requestPermission(). 

checkPermission() method is using to check app have permission or not,
If the method return true means app have permission and return false means app doesn’t have permission, in that case we will call requestPermission()method to ask the permission at runtime.

5. Open MainActivity.java   

public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 123;

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

boolean check=checkPermission();
if (check) {
Toast.makeText(this, "Permission already granted.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission not granted.", Toast.LENGTH_SHORT).show();
requestPermission();
}
}

private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),READ_CONTACTS);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),WRITE_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
}

private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{READ_CONTACTS, WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE:
if (grantResults.length > 0) {
boolean contactAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean storageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (contactAccepted && storageAccepted)
Toast.makeText(this, "Permission granted by user.", Toast.LENGTH_SHORT).show();
else {
Toast.makeText(this, "Permission denied by user.", Toast.LENGTH_SHORT).show();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{READ_CONTACTS, WRITE_EXTERNAL_STORAGE},
REQUEST_CODE);
}
}
});
return;
}
}
}
}
break;
}
}

private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
}
6. All coding work are done. Now its time to check our app is working/running perfectly.
In the below link you will find full code.



Post a Comment

0 Comments