Thursday, 4 April 2019

How to take single permission in android at runtime | How to show DialogBox with grant and cancel option before taking run time permission in android.

on the click on specific button we have do like following :-

actionButton.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {
        if(ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) 
!= PackageManager.PERMISSION_GRANTED) {
            //Show Information about why you need the permission            
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Need Storage Permission");
            builder.setMessage("This app needs storage permission.");
            builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                @Override                
public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                    ActivityCompat.requestPermissions(MainActivity.this
,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},200);
                }
            });

            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override                
public void onClick(DialogInterface dialog, int which) {
                  dialog.cancel();
                }
            });
            builder.show();

        }else {
            //just request the permission            
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},200);
        }
    }
});

@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
 @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode){
        case 200:
            Toast.makeText(this,"Access denied",Toast.LENGTH_LONG).show();
            break;
    }
}



No comments:

Post a Comment