Tuesday, April 12, 2016

Handle Android Permission Dynamically @Run Time

Hi ... Dear All .. I hope you observed that now a days if you are going to install a new app a dialog box is popped up for asking permissions. Means we are handling the permission request at run time (Dynamically).

Generally we added permissions in manifest file but user must be aware that what kind of access is allowing to newly installed app.

 Please Like & put your valuable suggestions in comment box.


In the below given example permission for sending SMS will be handled at run time 

A. First Screen when app is going to start 


B. Manifest File 
You have to request for the required permissions like 
<uses-permission android:name="android.permission.SEND_SMS"/>
C. Main Activity Code 
package com.example.permissionissue;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
final int REQUEST_CODE_ASK_PERMISSIONS=123;
int permissionstatuscheck;
Boolean flag = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
permissionstatuscheck = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.SEND_SMS);

}

@Override
protected void onStart() {
super.onStart();
if(permissionstatuscheck == PackageManager.PERMISSION_GRANTED)
{
// Permission Already given to your App
Toast.makeText(this,"Permision Already Given",Toast.LENGTH_LONG).show();
flag = true;

}
else
{
askforPermission();
}
}

private void askforPermission() {

if(permissionstatuscheck != PackageManager.PERMISSION_GRANTED)
{
if(!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.SEND_SMS))
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.SEND_SMS},
REQUEST_CODE_ASK_PERMISSIONS);
return;
}
else
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.SEND_SMS},
REQUEST_CODE_ASK_PERMISSIONS);
}
}
}

@Override
public void onRequestPermissionsResult(int requestCode,String[] permissions,
int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == REQUEST_CODE_ASK_PERMISSIONS)
{
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
// Requested Permission Granted
Toast.makeText(this,"Permission Granted",Toast.LENGTH_LONG).show();
flag = true;

}
}
}
}

No comments:

Post a Comment