Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble in asking multiple permission in android Marshmallow

I am working on an app in which I want to ask multiple permission at run time. My code is worked fine for one Permission. However when I want to ask for multiple permission my code does nothing . Can anyone tell me what wrong with my code?

package saleskit.orbitsys.com.androidpermissiondemo;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_INTERNET = 200;
    private static final int REQUEST_CODE_INTERNET = 110;
    private static final int PERMISSION_REQUEST_CODE_GPS = 111;
    public static final int PERMISSION_REQUEST_CODE_CONTACT = 112;
    public static final int PERMISSION_REQUEST_CODE_CAMARA = 113;
    public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 201;
    private WebView htmlWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar
                = getSupportActionBar();
        if (null != actionBar) {
            actionBar.hide();
        }
checkMultiplePermission();

       /* if (ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{ Manifest.permission.RECORD_AUDIO}, REQUEST_INTERNET);
        }*/


        htmlWebView = (WebView) findViewById(R.id.webView);
        assert htmlWebView != null;
        WebSettings webSetting = htmlWebView.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setDisplayZoomControls(true);
        htmlWebView.setWebViewClient(new CustomWebViewClient());
        htmlWebView.loadUrl("https://inducesmile.com/blog");

    }

    public boolean checkMultiplePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                int permissionFineLocation = ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION);
                int permissionCorseLocation = ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.ACCESS_COARSE_LOCATION);
                int permissioncamera = ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.CAMERA);
                int permissioncall = ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.CALL_PHONE);
                int permissionSDCARD = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                int permissionSDCARD2 = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE);
                int readSms = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_SMS);
                List<String> listPermissionsNeeded = new ArrayList<>();
                if (permissioncall != PackageManager.PERMISSION_GRANTED) {
                    listPermissionsNeeded.add(Manifest.permission.CALL_PHONE);
                }
                if (permissionCorseLocation != PackageManager.PERMISSION_GRANTED) {
                    listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                }
                if (permissionFineLocation != PackageManager.PERMISSION_GRANTED) {
                    listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
                }
                if (permissioncamera != PackageManager.PERMISSION_GRANTED) {
                    listPermissionsNeeded.add(Manifest.permission.CAMERA);
                }
                if (permissionSDCARD != PackageManager.PERMISSION_GRANTED) {
                    listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }
                if (permissionSDCARD2 != PackageManager.PERMISSION_GRANTED) {
                    listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
                }
                if (readSms != PackageManager.PERMISSION_GRANTED) {
                    listPermissionsNeeded.add(Manifest.permission.READ_SMS);
                }

                if (!listPermissionsNeeded.isEmpty()) {
                    ActivityCompat.requestPermissions(MainActivity.this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
                    return false;
                }

                return true;
            } else {
                return true;
            }
        }





    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] listPermissionsNeeded, @NonNull int[] grantResults) {
        if(listPermissionsNeeded.length == 0){
            return;
        }
        boolean allPermissionsGranted = true;
        if(grantResults.length>0){
            for(int grantResult: grantResults){
                if(grantResult != PackageManager.PERMISSION_GRANTED){
                    allPermissionsGranted = false;
                    break;
                }
            }
        }
        if(!allPermissionsGranted){
            boolean somePermissionsForeverDenied = false;
            for(String permission: listPermissionsNeeded){
                if(ActivityCompat.shouldShowRequestPermissionRationale(this, permission)){
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{ permission}, requestCode);
                    //denied
                    Log.e("denied", permission);
                }else{
                    if(ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED){
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{ permission}, requestCode);

                        //allowed
                        Log.e("allowed", permission);
                    } else{


                        somePermissionsForeverDenied = true;
                    }
                }
            }
            if(somePermissionsForeverDenied){
                 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                alertDialogBuilder.setTitle("Permissions Required")
                        .setMessage("You have forcefully denied some of the required permissions " +
                                "for this action. Please open settings, go to permissions and allow them.")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                                        Uri.fromParts("package", getPackageName(), null));
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            }
                        })


                        .show();
            }
        } else {
            switch (requestCode) {
                //act according to the request code used while requesting the permission(s).
            }
        }
    }
    private class CustomWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
}

Any kind of help is appreciate by me thanks.

like image 600
Abhishek Bhardwaj Avatar asked Oct 29 '22 14:10

Abhishek Bhardwaj


2 Answers

First check permission is already granted or not.

Here you can check more then one permissions.

if (checkForPermission(getActivity(), CAMERA_PERMISSION) && checkForPermission(getActivity(), GALLERY_PERMISSION)) {
      //Permission granted here
      //TODO

    } else {
        requestPermissions(new String[]{CAMERA_PERMISSION, GALLERY_PERMISSION}, 1);
}

checkForPermission method.

/***
 * Method is checking permission for Marshmallow
 *
 * @param context
 * @param permission
 * @return
 */
private static boolean checkForPermission(final Context context, String permission) {
    int result = ContextCompat.checkSelfPermission(context, permission);
    //If permission is granted then it returns 0 as result
    if (result == PackageManager.PERMISSION_GRANTED) {
        return true;
    } else {
        return false;
    }
}

onRequestPermissionsResult method its like onActivityResult.

/***
 * This is call when user allow or deny permissions in the Marshmallow
 *
 * @param requestCode
 * @param permissions
 * @param grantResults
 */
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case 1:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
               //Permission granted here
               //TODO

            }
            break;
    }
}
like image 97
Foram Shah Avatar answered Nov 09 '22 09:11

Foram Shah


In your activity:

private static final int MY_PERMISSIONS = 111;

in onCreate method:

String[] mPermissionToRequest = new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.CAMERA,Manifest.permission.CALL_PHONE};

ActivityCompat.requestPermissions(this, mPermissionsToRequest, MY_PERMISSIONS);

@Override

public void onRequestPermissionsResult( int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

}

Check for your AndroidManifest.xml file:

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

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

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
like image 41
Patrick R Avatar answered Nov 09 '22 07:11

Patrick R