<p>Every Android application is started in its own process thus are isolated from all other applications (even from system/default applications). As a result, an Android application can’t access any file or data outside its scope until and unless the file or data is shared with the application.</p>
<p>So, the conclusion is that if an application needs anything outside its scope, then it has to request the appropriate permission<i>.</i></p>
<p><em><strong>Get <span style="color: #008000;">Github</span> code from</strong> <span style="color: #0000ff;"><strong><a style="color: #0000ff;" href="https://github.com/arunk7839/RuntimePermissionDemo">HERE</a></strong>.</span> </em></p>
<p><span class="embed-youtube" style="text-align:center; display: block;"><amp-youtube data-videoid="hgJnQYIg_eM" data-param-rel="1" data-param-showsearch="0" data-param-showinfo="1" data-param-iv_load_policy="1" data-param-fs="1" data-param-hl="en-US" data-param-autohide="2" data-param-wmode="transparent" width="1200" height="675" layout="responsive"><a href="https://www.youtube.com/watch?v=hgJnQYIg_eM" placeholder><amp-img src="https://i.ytimg.com/vi/hgJnQYIg_eM/hqdefault.jpg" alt="YouTube Poster" layout="fill" object-fit="cover"><noscript><img src="https://i.ytimg.com/vi/hgJnQYIg_eM/hqdefault.jpg" loading="lazy" decoding="async" alt="YouTube Poster"></noscript></amp-img></a></amp-youtube></span></p>
<h3><strong><span style="color: #000080;">Android Runtime Permissions</span></strong></h3>
<ul>
<li><span style="color: #008000;"><strong>Runtime permissions</strong></span> are a new feature in Android 6.0 Marshmallow that allow you to request permissions at runtime, when it matters rather than at install time.</li>
<li>This will give the user to have more control over the permissions and ensure more security for his/her confidential data.</li>
<li>In the case we try to call some function that requires a permission which user has not granted yet, the function will suddenly throw an Exception <strong><span style="color: #0000ff;">(java.lang.SecurityException)</span></strong> that will lead to the application crashing. Hence we need to implement this new android permissions model in our application.</li>
</ul>
<h3><span style="color: #000080;"><strong>Permission Types</strong></span></h3>
<p class="p1">Permissions are divided into several protection levels. The two most important protection levels are normal and dangerous permissions.</p>
<ul>
<li class="p1"><span style="color: #000080;"><b>Normal Permissions</b></span></li>
<li><span style="color: #000080;"><b>Dangerous Permissions</b></span></li>
</ul>
<p class="p1"><b><span style="color: #0000ff;">Normal Permissions</span>:</b> Permissions that have very little or no effect on user&#8217;s privacy or confidential data are categorized as normal permissions. The system itself grants normal permissions when requested instead of prompting to the user. Examples would be <span style="color: #008000;"><b>ACCESS_WIFI_STATE</b>, <b>WAKE_LOCK,</b> </span><strong><span style="color: #008000;">INTERNET</span>, </strong>etc.</p>
<p class="p1"><strong><span style="color: #0000ff;">Dangerous Permissions</span></strong><b>:</b> Permissions that may have a greater effect on user&#8217;s privacy or confidential data are categorized as dangerous permissions. Examples would be <b><span style="color: #008000;">READ_CONTACTS, ACCESS_FINE_LOCATION, CAMERA</span>, </b>etc. If an app requests dangerous permissions then the user has to explicitly grant permission to the app.</p>
<p class="p1">Here is the detailed <span style="color: #0000ff;"><strong><a style="color: #0000ff;" href="https://developer.android.com/guide/topics/security/permissions.html#normal-dangerous"><span class="s1">information</span></a></strong></span> about permissions.</p>
<h3 class="p1"><span style="color: #000080;"><b>Permission Workflow before and from M (API 23)</b></span></h3>
<p class="p2">The permission workflow has been changed from Android Marshmallow(API 23). The way Android asks the user to grant dangerous permissions depends on the version of Android running on the user&#8217;s device, and the system version targeted by your app.</p>
<p><b> <span style="color: #0000ff;">Permission Model before M (API 23):</span></b><span style="color: #0000ff;"> </span></p>
<ul>
<li>Before API 23, the permission model was simpler to the developer but offered less control and security to the user.</li>
<li>If the device is running Android 5.1.1 (API level 22) or lower, <em>or</em> the app&#8217;s <strong><span style="color: #008000;">targetSdkVersion</span></strong> is 22 or lower while running on any version of Android, the system automatically asks the user to grant all dangerous permissions for your app at install-time.</li>
</ul>
<figure id="attachment_1261" aria-describedby="caption-attachment-1261" style="width: 323px" class="wp-caption aligncenter"><img class="alignnone size-full wp-image-1261" src="https://i2.wp.com/c1ctech.com/wp-content/uploads/2019/10/Screenshot-2019-10-22-19.58.41-2154046784-1571817449429.png?ssl=1&;w=646" alt="Screenshot 2019-10-22 19.58.41" width="323" height="574" /><figcaption id="caption-attachment-1261" class="wp-caption-text">Install-time permission dialog</figcaption></figure>
<ul>
<li>If the user clicks <span style="color: #008000;"><strong>Accept</strong></span>, all permissions the app requests are granted. If the user denies the permissions request, the system cancels the installation of the app.</li>
<li>Permissions cannot be denied or granted after the installation.</li>
<li>Thus developers were required only to declare all needed permissions in the manifest and then just forget, if the app is running then it has all the requested permissions.</li>
</ul>
<p><b><span style="color: #0000ff;">Permission Model from M (API 23):</span></b><span style="color: #0000ff;"> </span></p>
<ul>
<li>With Android 6.0 Marshmallow (API 23), a new runtime permission model has been introduced.</li>
<li>According to this model if the device is running Android 6.0 (API level 23) or higher, and the app&#8217;s <strong><span style="color: #008000;">targetSdkVersion</span></strong> is 23 or higher, the user isn&#8217;t notified of any app permissions at install time.</li>
<li>Your app must ask the user to grant the dangerous permissions at runtime before performing any action that may require the particular permission.</li>
<li>When your app requests permission, the user sees a system dialog which includes a <span style="color: #008000;"><b>Deny</b></span> and <span style="color: #008000;"><b>Allow</b></span> button.</li>
<li>If the user denies the permission request, the next time your app requests the permission, the dialog contains a checkbox that, when checked, indicates the user doesn&#8217;t want to be prompted for the permission again.</li>
</ul>
<p><img class="alignnone wp-image-1251" src="https://c1ctech.com/wp-content/uploads/2019/10/Screenshot_1571749993.png" alt="Screenshot_1571749993" width="316" height="562" /> <img class="alignnone wp-image-1254" src="https://c1ctech.com/wp-content/uploads/2019/10/Screenshot_1571750449.png" alt="Screenshot_1571750449" width="315" height="560" /></p>
<p class="p2"><span style="color: #0000ff;"><b>Note:</b> </span>According to Google, beginning with Android 6.0 (API level 23), users can revoke permissions from any app at any time, even if the app targets a lower API level.</p>
<h3><strong><span style="color: #000080;">Check for permission</span></strong></h3>
<p>If your app needs a dangerous permission, then you must check whether you have that permission or not every time when the app performs an operation that requires that permission.</p>
<p><strong><span style="color: #0000ff;">For example</span></strong>, if your app uses the camera feature, then you have to check for the camera permission every time when app opens the camera.</p>
<p>To check if you have a permission, call the <span style="color: #008000;"><strong><span class="pln">checkSelfPermission()</span></strong></span> method. For example, this snippet shows how to check if the activity has permission to access the camera and location:</p>
<pre>private boolean checkPermission() {

<span class="typ"><strong><span style="color: #0000ff;">//Assume thisActivity as current activity</span></strong></span>
 int result1 = ContextCompat.checkSelfPermission(<span class="pln">thisActivity</span>, <span class="typ">Manifest</span><span class="pun">.</span><span class="pln">permission</span><span class="pun">.</span>ACCESS_FINE_LOCATION);
 int result2 = ContextCompat.checkSelfPermission(<span class="pln">thisActivity</span>, <span class="typ">Manifest</span><span class="pun">.</span><span class="pln">permission</span><span class="pun">.</span>CAMERA);

 return result1 == PackageManager.PERMISSION_GRANTED &;&; result2 == PackageManager.PERMISSION_GRANTED;
}</pre>
<p>If the app has permission, then the method returns <strong><span style="color: #008000;">packageManager.PERMISSION_GRANTED</span></strong> (ie. 0) and the app can continue with the operation.</p>
<p>If the app does not have permission, then the method returns <strong><span style="color: #008000;">packageManager.PERMISSION_DENIED</span> </strong>(ie. -1) and the app have to explicitly ask the user for permission.</p>
<h3 id="explain"><strong><span style="color: #000080;">Explain why the app needs permissions</span></strong></h3>
<p>In some circumstances, you want to help the user understand why your app needs a permission.</p>
<p><strong><span style="color: #0000ff;">For example</span></strong>, if you write a camera app, requesting the camera permission would be expected by the user and no rationale for why it is requested is needed. If however, the app needs location for tagging photos then a non-tech savvy user may wonder how location is related to taking photos. In this case, you may choose to show UI with rationale of requesting this permission.</p>
<p>Android provides a utility method, <span style="color: #0000ff;"><strong>shouldShowRequestPermissionRationale()</strong></span>, that returns <span style="color: #008000;"><strong>true</strong></span> if the user has previously denied the request, and returns <strong><span style="color: #008000;">false</span></strong> if a user has denied a permission and selected the <span style="color: #008000;"><strong>Don&#8217;t ask again</strong></span> option in the permission request dialog, or if a device policy prohibits the permission.</p>
<pre>if (Build.VERSION.SDK_INT >;= Build.VERSION_CODES.M) {

<strong><span style="color: #0000ff;">//shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION) || </span></strong>
<strong><span style="color: #0000ff;">shouldShowRequestPermissionRationale(CAMERA) returns true if 
the user has previously denied any of the request</span></strong>
 if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION) || shouldShowRequestPermissionRationale(CAMERA)) {

 showMessageGrantCancel("You need to allow access to both the permissions",
 new DialogInterface.OnClickListener() {
 @Override
 public void onClick(DialogInterface dialog, int which) {
 
<strong><span style="color: #0000ff;">//when the user click on grant button then 
requestPermission() will call requesting array of permissions. </span> </strong>
if (Build.VERSION.SDK_INT >;= Build.VERSION_CODES.M) {
 requestPermissions(new String[]{ ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION, CAMERA}, PERMISSION_REQUEST_CODE);
 }
 }
 });
 } 
}

<strong><span style="color: #0000ff;">//showMessageGrantCancel() will show an alert dialog with rationale of </span></strong>
<span style="color: #0000ff;"><strong>requesting this permissions</strong></span>
private void showMessageGrantCancel(String message, DialogInterface.OnClickListener okListener) {
 new AlertDialog.Builder(MainActivity.this)
 .setMessage(message)
 .setPositiveButton("GRANT", okListener)
 .setNegativeButton("CANCEL", null)
 .create()
 .show();
}

</pre>
<h3></h3>
<h3><strong><span style="color: #000080;">Request and Handle Runtime permission</span></strong></h3>
<p>When your app receives <strong><span style="color: #008000;">PERMISSION_DENIED</span></strong> from <strong><span style="color: #0000ff;">checkSelfPermission()</span></strong>, you need to prompt the user for that permission. To request the permissions Android provides a method called <strong><span style="color: #0000ff;">requestPermissions()</span></strong> to request array of permissions to be granted to the application and these permissions must be requested in your manifest. Calling these methods brings up a standard Android dialog, which you cannot customize. When the user responds to your app&#8217;s permission request, the system invokes your app&#8217;s <strong><span style="color: #0000ff;">onRequestPermissionsResult()</span></strong> method, passing it the user response.</p>
<h4><strong><span style="color: #000080;">Request runtime permission</span></strong></h4>
<ul>
<li>If your app doesn&#8217;t already have the permission it needs, the app must call one of the <strong><span style="color: #0000ff;">requestPermissions()</span></strong> methods to request the appropriate permissions.</li>
<li>Your app passes the permissions it wants and an integer <span style="color: #008000;"><strong>request code</strong></span> that you specify to identify this permission request.</li>
<li>This method functions asynchronously. It returns right away, and after the user responds to the prompt.</li>
<li>The system calls the app&#8217;s callback method <span style="color: #0000ff;"><strong>onRequestPermissionsResult()</strong></span> with the results, passing the same request code that the app passed to <strong><span style="color: #0000ff;">requestPermissions()</span></strong>.</li>
</ul>
<p>The following code checks if the app has permission to access <strong><span style="color: #008000;">CAMERA</span></strong>. If it does not have permission it checks if it should show an explanation for needing the permission, and if no explanation is needed, it requests the permission:</p>
<pre><strong><span style="color: #0000ff;">// Here, thisActivity is the current activity</span></strong>
if (ContextCompat.checkSelfPermission(thisActivity,
 Manifest.permission.CAMERA)
 != PackageManager.PERMISSION_GRANTED) {

 /<strong><span style="color: #0000ff;">/ Permission is not granted</span></strong>
<strong><span style="color: #0000ff;"> // Should we show an explanation?</span></strong>
 if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
 Manifest.permission.CAMERA)) {
 <strong><span style="color: #0000ff;">// Show an explanation to the user *asynchronously* -- don't block</span></strong>
<strong><span style="color: #0000ff;"> // this thread waiting for the user's response! After the user</span></strong>
<strong><span style="color: #0000ff;"> // sees the explanation, try again to request the permission.</span></strong>
 } else {
 <strong><span style="color: #0000ff;">// No explanation needed; request the permission</span></strong>
 ActivityCompat.requestPermissions(thisActivity,
 new String[]{ Manifest.permission.CAMERA},PERMISSION_REQUEST_CODE);

<strong><span style="color: #0000ff;">//PERMISSION_REQUEST_CODE is an</span></strong>
<strong><span style="color: #0000ff;">// app-defined int constant. The callback method gets the</span></strong>
<strong><span style="color: #0000ff;">// result of the request.</span></strong>
}
} else {
<strong><span style="color: #0000ff;">// Permission has already been granted</span></strong>
}</pre>
<h4 id="handle-response"><span style="color: #000080;"><strong>Handle the permissions request response</strong></span></h4>
<ul>
<li>When the user responds to your app&#8217;s permission request, the system invokes your app&#8217;s <strong><span style="color: #0000ff;">onRequestPermissionsResult()</span></strong> method, passing it the user response. Your app has to override that method to find out whether the permission was granted. The callback is passed the same request code you passed to <strong><span style="color: #0000ff;">requestPermissions()</span></strong>.</li>
</ul>
<p>For example, if an app requests <span style="color: #008000;"><strong>CAMERA</strong></span> and <span style="color: #008000;"><strong>LOCATION</strong></span> access it might have the following callback method:</p>
<pre>@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
 switch (requestCode) {
 case PERMISSION_REQUEST_CODE:

<span class="com"><strong><span style="color: #0000ff;">// If request is cancelled, the result arrays are empty.</span></strong>
</span>if (grantResults.length >; 0) {

boolean AcceptedFineLocation = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean AcceptedCamera = grantResults[1] == PackageManager.PERMISSION_GRANTED;

if (AcceptedFineLocation &;&; AcceptedCamera)
Toast.makeText(this, "Permission Granted, Now you can access location data and camera.", Toast.LENGTH_LONG).show();

else {
Toast.makeText(this, "Permission Denied, You cannot access location data and camera.", Toast.LENGTH_LONG).show();
}
}
break;
}
}</pre>
<ul>
<li>If the user denies a permission request, your app should take appropriate action. For example, your app might show a dialog explaining why it could not perform the user&#8217;s requested action that needs that permission.</li>
<li>When the system asks the user to grant a permission, the user has the option of telling the system not to ask for that permission again. In that case, any time an app uses <span style="color: #0000ff;"><strong>requestPermissions()</strong></span> to ask for that permission again, the system immediately denies the request.</li>
</ul>
<h3><strong><span style="color: #000080;">Understand the workflow of runtime permission request</span></strong></h3>
<ul>
<li>When the app asks for dangerous permission for the first time, then the system shows a standard non-customizable dialog that specifies the permission features.</li>
</ul>
<p><img class="alignnone wp-image-1250" src="https://c1ctech.com/wp-content/uploads/2019/10/Screenshot_1571749987-576x1024.png" alt="Screenshot_1571749987" width="303" height="539" /> <img class="alignnone wp-image-1251" src="https://c1ctech.com/wp-content/uploads/2019/10/Screenshot_1571749993.png" alt="Screenshot_1571749993" width="301" height="535" /></p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>

<ul>
<li>If the user denies permission and the app tries to access the same permission again then it is a good programming practice to show an explanation to the user that why the app needs that permission. This is not a system dialog but showing explanation is the responsibility of the user.</li>
</ul>
<p><img class=" wp-image-1253 aligncenter" src="https://c1ctech.com/wp-content/uploads/2019/10/Screenshot_1571750324.png" alt="Screenshot_1571750324" width="321" height="571" /></p>
<ul>
<li>If a previously denied permission request again, then the system shows a standard dialog with an additional <strong><span style="color: #008000;">checkbox (Don&#8217;t ask again)</span></strong>.</li>
<li>If the user selects the checkbox(Don&#8217;t ask again) then the system will never show that permission dialog again.</li>
</ul>
<p><img class=" wp-image-1257 aligncenter" src="https://c1ctech.com/wp-content/uploads/2019/10/Screenshot_1571750895.png" alt="Screenshot_1571750895" width="319" height="567" /></p>
<ul>
<li>If the user selects the checkbox(Don&#8217;t ask again) and denies the permission for the second time then it is a good programming practice to lead the user to the permission page in app settings to grant the denied permissions.</li>
</ul>
<p><img class="alignnone wp-image-1255" src="https://c1ctech.com/wp-content/uploads/2019/10/Screenshot_1571750569.png" alt="Screenshot_1571750569" width="320" height="569" /> <img class="alignnone wp-image-1256" src="https://c1ctech.com/wp-content/uploads/2019/10/Screenshot_1571750591.png" alt="Screenshot_1571750591" width="320" height="569" /></p>
<p>So now let us start with creating a sample app.</p>
<h3><strong><span style="color: #000080;">Creating Android Project</span></strong></h3>
<p><strong>1</strong>. Create a new project in Android Studio from <span style="color: #008000;"><strong>File ⇒ New Project</strong> </span>and fill the project details.</p>
<p><strong>2</strong>. Open <strong>build.gradle</strong> (app level) and make sure that you have set <span style="color: #008000;"><strong>minSdkVersion</strong></span> and <span style="color: #008000;"><strong>targetSdkVersion</strong></span> as we have to support the permissions model in lower versions also. I am keeping minSdkVersion to <strong>17</strong> and targetSdkVersion to <strong>28</strong>.</p>
<p><span style="color: #0000ff;"><strong>build.gradle</strong></span></p>
<div>
<pre>apply plugin: 'com.android.application'

android {
 compileSdkVersion 28
 defaultConfig {
 ....

 minSdkVersion 17
 targetSdkVersion 28

 ....
 
 }</pre>
</div>
<p><strong>3</strong>. Though we will request the permissions at runtime, we should add it to the Manifest also. We will start with the <strong><span style="color: #008000;">CAMERA</span></strong> and <span style="color: #008000;"><strong>ACCESS_FINE_LOCATION</strong></span> permissions. Add these permissions to your <span style="color: #008000;"><strong>AndroidManifest.xml</strong></span> just before the application tag.</p>
<p><span style="color: #0000ff;"><strong>AndroidManifest.xml</strong></span><!--?xml version="1.0" encoding="utf-8"?--><!--?xml version="1.0" encoding="utf-8"?--><!--?xml version="1.0" encoding="utf-8"?--></p>
<pre><;?xml version="1.0" encoding="utf-8"?>;
<;manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="trendlife.myapplication">;
 <;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>;
 <;uses-permission android:name="android.permission.CAMERA"/>;
 

 <;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>;</pre>
<p><strong>4</strong>. Open the layout file of main activity (<strong>activity_main.xml</strong>) and add the below xml. This layout contains two buttons ie. <strong><span style="color: #008000;">CHECK PERMISSION</span></strong> to check the permission and <span style="color: #008000;"><strong>REQUEST PERMISSION</strong></span> to request the permissions.</p>
<p><span style="color: #0000ff;"><strong>activity_main.xml</strong></span></p>
<pre><;?xml version="1.0" encoding="utf-8"?>;
<;LinearLayout 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"
 android:gravity="center"
 android:orientation="vertical"
 tools:context=".MainActivity">;

 <;Button
 android:id="@+id/check_permission"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:background="@color/colorAccent"
 android:padding="8dp"
 android:text="Check Permission" />;

 <;Button
 android:id="@+id/request_permission"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginTop="10dp"
 android:background="@color/colorAccent"
 android:padding="8dp"
 android:text="Request Permission" />;


<;/LinearLayout>;</pre>
<p><span style="color: var(--color-text);">The above layout generates a screen something like this.</span></p>
<div></div>
<div><img class=" wp-image-1259 aligncenter" src="https://c1ctech.com/wp-content/uploads/2019/10/Screenshot_1571751672.png" alt="Screenshot_1571751672" width="366" height="651" /></div>
<div></div>
<div></div>
<div><strong>5</strong>. Now open <span style="color: #0000ff;"><strong>MainActivity.java</strong></span> and write the below code on <span style="color: #008000;"><strong>CHECK PERMISSION</strong></span> button click :</div>
<div></div>
<div>
<pre>public void onClick(View v) {


 int id = v.getId();
 switch (id) {
 case R.id.check_permission:
 if (checkPermission()) {

 Toast.makeText(this, "Permission already granted.", Toast.LENGTH_LONG).show();

 } else {
 Toast.makeText(this, "Please request permission.", Toast.LENGTH_LONG).show();

 }
 break;
 }
 }


private boolean checkPermission() {
 int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION);
 int result2 = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);

 return result1 == PackageManager.PERMISSION_GRANTED &;&; result2 == PackageManager.PERMISSION_GRANTED;
}</pre>
</div>
<div></div>
<div>6. In <span style="color: #0000ff;"><strong>MainActivity.java</strong></span> write the below code on <span style="color: #008000;"><strong>REQUEST PERMISSION</strong></span> button click :</div>
<div></div>
<div>
<pre>public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private static final int PERMISSION_REQUEST_CODE = 200;

@Override
public void onClick(View v) {


int id = v.getId();
switch (id) {

case R.id.request_permission:
if (!checkPermission()) {

requestPermission();

} else {
Toast.makeText(this, "Permission already granted.", Toast.LENGTH_LONG).show();


}
break;
}

}


private void requestPermission() {

ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION, CAMERA}, PERMISSION_REQUEST_CODE);

}


}</pre>
</div>
<div></div>
<div>7. When the user responds to your app&#8217;s permission request, the system invokes your</div>
<div>app&#8217;s <strong><span style="color: #0000ff;">onRequestPermissionsResult()</span></strong> method corresponding to the request code, and passing it the user response.</div>
<div></div>
<div>
<pre>@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
 switch (requestCode) {
 case PERMISSION_REQUEST_CODE:
 if (grantResults.length >; 0) {

 boolean AcceptedFineLocation = grantResults[0] == PackageManager.PERMISSION_GRANTED;
 boolean AcceptedCamera = grantResults[1] == PackageManager.PERMISSION_GRANTED;

 if (AcceptedFineLocation &;&; AcceptedCamera)
 Toast.makeText(this, "Permission Granted, Now you can access location data and camera.", Toast.LENGTH_LONG).show();

 else {
 Toast.makeText(this, "Permission Denied, You cannot access location data and camera.", Toast.LENGTH_LONG).show();


 if (Build.VERSION.SDK_INT >;= Build.VERSION_CODES.M) {
 if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION) || shouldShowRequestPermissionRationale(CAMERA)) {

 showMessageGrantCancel("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[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION, CAMERA}, PERMISSION_REQUEST_CODE);
 }
 }
 });
 return;
 } else {
 openSettingsDialog();
 }
 }

 }
 }


 break;
 }

}</pre>
</div>
<div></div>
<div>8. Below is the complete code of <strong><span style="color: #008000;">MainActivity.java</span>.</strong></div>
<div></div>
<div><span style="color: #0000ff;"><strong>MainActivity.java</strong></span></div>
<div></div>
<div>
<pre>package trendlife.myapplication;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.CAMERA;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

 private static final int PERMISSION_REQUEST_CODE = 200;


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


 Button check_permission = (Button) findViewById(R.id.check_permission);
 Button request_permission = (Button) findViewById(R.id.request_permission);
 check_permission.setOnClickListener(this);
 request_permission.setOnClickListener(this);


 }


 @Override
 public void onClick(View v) {


 int id = v.getId();
 switch (id) {
 case R.id.check_permission:
 if (checkPermission()) {

 Toast.makeText(this, "Permission already granted.", Toast.LENGTH_LONG).show();

 } else {
 Toast.makeText(this, "Please request permission.", Toast.LENGTH_LONG).show();

 }
 break;
 case R.id.request_permission:
 if (!checkPermission()) {

 requestPermission();

 } else {
 Toast.makeText(this, "Permission already granted.", Toast.LENGTH_LONG).show();


 }
 break;
 }

 }

 private boolean checkPermission() {
 int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION);
 int result2 = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);

 return result1 == PackageManager.PERMISSION_GRANTED &;&; result2 == PackageManager.PERMISSION_GRANTED;
 }


 private void requestPermission() {

 ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION, CAMERA}, PERMISSION_REQUEST_CODE);

 }

 @Override
 public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
 switch (requestCode) {
 case PERMISSION_REQUEST_CODE:
 if (grantResults.length >; 0) {

 boolean AcceptedFineLocation = grantResults[0] == PackageManager.PERMISSION_GRANTED;
 boolean AcceptedCamera = grantResults[1] == PackageManager.PERMISSION_GRANTED;

 if (AcceptedFineLocation &;&; AcceptedCamera)
 Toast.makeText(this, "Permission Granted, Now you can access location data and camera.", Toast.LENGTH_LONG).show();

 else {
 Toast.makeText(this, "Permission Denied, You cannot access location data and camera.", Toast.LENGTH_LONG).show();


 if (Build.VERSION.SDK_INT >;= Build.VERSION_CODES.M) {
 if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION) || shouldShowRequestPermissionRationale(CAMERA)) {

 showMessageGrantCancel("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[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION, CAMERA}, PERMISSION_REQUEST_CODE);
 }
 }
 });
 return;
 } else {
 openSettingsDialog();
 }
 }

 }
 }


 break;
 }

 }


 private void showMessageGrantCancel(String message, DialogInterface.OnClickListener okListener) {
 new AlertDialog.Builder(MainActivity.this)
 .setMessage(message)
 .setPositiveButton("GRANT", okListener)
 .setNegativeButton("CANCEL", null)
 .create()
 .show();
 }

 private void openSettingsDialog() {

 AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
 builder.setTitle("Required Permissions");
 builder.setMessage("This app require permission to use awesome feature. Grant them in app settings.");
 builder.setPositiveButton("Take Me To SETTINGS", new DialogInterface.OnClickListener() {
 @Override
 public void onClick(DialogInterface dialog, int which) {
 dialog.cancel();
 Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
 Uri uri = Uri.fromParts("package", getPackageName(), null);
 intent.setData(uri);
 startActivityForResult(intent, 101);
 }
 });
 builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
 @Override
 public void onClick(DialogInterface dialog, int which) {
 dialog.cancel();
 }
 });
 builder.show();

 }
}


</pre>
</div>
<div></div>
<div><strong>I hope this article gave you a good overview of Marshmallow permission model. Feel free to ask any queries / doubts in comments section below.</strong></div>
<div></div>
<div></div>


