Android 6.0 multiple permissions

后端 未结 22 1872
太阳男子
太阳男子 2020-11-22 03:58

I know that Android 6.0 has new permissions and I know I can call them with something like this

if (ContextCompat.checkSelfPermission(this, Manifest.permiss         


        
相关标签:
22条回答
  • 2020-11-22 04:16

    You can use Dexter

    In build.gradle add:

    implementation 'com.karumi:dexter:5.0.0'
    

    And use it in your activity as:

    val requiredPermissions = when {
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> listOf(Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_BACKGROUND_LOCATION)
                else -> listOf(Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION)
            }
    
    Dexter.withActivity(this)
         .withPermissions(
               requiredPermissions
          )
         .withListener(object : MultiplePermissionsListener {
            override fun onPermissionRationaleShouldBeShown(
                 permissions: MutableList<PermissionRequest>?,
                        token: PermissionToken?
                 ) {
                        /* ... */
                    }
    
    
            override fun onPermissionsChecked(report: MultiplePermissionsReport) = 
                 if (report.isAnyPermissionPermanentlyDenied) {
                    toast("You should grant all permissions") 
                 } else {
                    toast("All permissions granted")
    
                    // continue here if permission is a must
    
                  }).check()
    
                 // continue here if permission is not a must
    
    0 讨论(0)
  • 2020-11-22 04:17

    My approach is based on Nicks' answer and hopefully is a bit more usable for multiple (as many as needed, not only two) permissions. It suggests adding single-responsibility PermissionsHelper class:

    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.pm.PackageManager;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.util.Log;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class PermissionsHelper {
    
    private static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 100; // any code you want.
    
    public void checkAndRequestPermissions(Activity activity, String... permissions) {
        List<String> listPermissionsNeeded = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(permission);
            }
        }
        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(activity, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
        }
    }
    
    public void onRequestPermissionsResult(Activity activity, int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_ID_MULTIPLE_PERMISSIONS: {
                Map<String, Integer> perms = new HashMap<>();
    
                for (String permission : permissions) {
                    perms.put(permission, PackageManager.PERMISSION_GRANTED);
                }
    
                if (grantResults.length > 0) {
                    for (int i = 0; i < permissions.length; i++)
                        perms.put(permissions[i], grantResults[i]);
    
                    boolean allPermissionsGranted = true;
                    for (String permission1 : permissions) {
                        allPermissionsGranted = allPermissionsGranted && (perms.get(permission1) == PackageManager.PERMISSION_GRANTED);
                    }
    
                    if (allPermissionsGranted) {
                        Log.d(PermissionsHelper.class.getSimpleName(), "onRequestPermissionsResult: all permissions granted");
                    } else {
                        for (String permission2 : perms.keySet())
                            if (perms.get(permission2) == PackageManager.PERMISSION_GRANTED)
                                perms.remove(permission2);
    
                        StringBuilder message = new StringBuilder("The app has not been granted permissions:\n\n");
                        for (String permission : perms.keySet()) {
                            message.append(permission);
                            message.append("\n");
                        }
                        message.append("\nHence, it cannot function properly." +
                                "\nPlease consider granting it this permission in phone Settings.");
    
                        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                        builder.setTitle(R.string.permission_required)
                                .setMessage(message)
                                .setPositiveButton(android.R.string.ok, (dialog, id) -> dialog.cancel());
                        AlertDialog alert = builder.create();
                        alert.show();
                    }
                }
            }
        }
    }
    

    }

    If one or several required permissions have not been granted by user, the detailed AlertDialog message will be shown to him.

    Example of usage in Activity:

    private PermissionsHelper permissionsHelper;
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        checkPermissions();
    
        //any other code
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        permissionsHelper.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }
    
    private void checkPermissions() {
        permissionsHelper = new PermissionsHelper();
        permissionsHelper.checkAndRequestPermissions(this,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION);
    }
    

    Hope that this will be useful for someone.

    0 讨论(0)
  • 2020-11-22 04:17

    I just use an array to achieved multiple requests, hope it helps someone. (Kotlin)

        // got all permission
        private fun requestPermission(){
            var mIndex: Int = -1
            var requestList: Array<String> = Array(10, { "" } )
    
            // phone call Permission
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                mIndex ++
                requestList[mIndex] = Manifest.permission.CALL_PHONE
            }
            // SMS Permission
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                mIndex ++
                requestList[mIndex] = Manifest.permission.SEND_SMS
            }
    
            // Access photos Permission
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                mIndex ++
                requestList[mIndex] = Manifest.permission.READ_EXTERNAL_STORAGE
            }
    
            // Location Permission
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                mIndex ++
                requestList[mIndex] = Manifest.permission.ACCESS_FINE_LOCATION
            }
    
            if(mIndex != -1){
                ActivityCompat.requestPermissions(this, requestList, PERMISSIONS_REQUEST_ALL)
            }
        }
    
    
        // permission response
        override fun onRequestPermissionsResult(requestCode: Int,
                                                permissions: Array<String>, grantResults: IntArray) {
            when (requestCode) {
                PERMISSIONS_REQUEST_ALL -> {
                    // If request is cancelled, the result arrays are empty.
                    if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        // permission accept location
                        if (ContextCompat.checkSelfPermission(this,
                                        Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                            Log.d(TAG, "Phone Call permission accept.")
                        }
    
                        // permission accept location
                        if (ContextCompat.checkSelfPermission(this,
                                        Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED) {
                            Log.d(TAG, "SMS permission accept.")
                        }
    
                        // permission accept location
                        if (ContextCompat.checkSelfPermission(this,
                                        Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                            Log.d(TAG, "SMS permission accept.")
                        }
    
                        // permission accept location
                        if (ContextCompat.checkSelfPermission(this,
                                        Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                            Log.d(TAG, "Location permission accept.")
                        }
    
                    } else {
                        Toast.makeText(mContext, "Permission Failed!", Toast.LENGTH_LONG).show()
                    }
                    return
                }
            }
        }
    
    0 讨论(0)
  • 2020-11-22 04:18

    In a Fragment

    public class Homefragment extends Fragment {
        View hfrag;
       Context context;
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
    //first we must check the permissions are already granted
    
            hfrag = inflater.inflate(R.layout.home, container, false);
            context = getActivity();
    checkAndRequestPermissions();
    
    }
    
    
    
    
    }
    
    
    private boolean checkAndRequestPermissions() {
            int permissionSendMessage = ContextCompat.checkSelfPermission(context,
                    Manifest.permission.READ_SMS);
            int contactpermission = ContextCompat.checkSelfPermission(context, Manifest.permission.GET_ACCOUNTS);
    
            int writepermission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    
            int callpermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE);
    
            int receivepermission = ContextCompat.checkSelfPermission(context, Manifest.permission.RECEIVE_SMS);
            int locationpermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
    
            List<String> listPermissionsNeeded = new ArrayList<>();
    
            if (locationpermission != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
    
            if (contactpermission != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.GET_ACCOUNTS);
            }
            if (writepermission != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.READ_SMS);
            }
            if (receivepermission != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.RECEIVE_SMS);
            }
    
            if (callpermission != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.CALL_PHONE);
            }
            if (!listPermissionsNeeded.isEmpty()) {
                requestPermissions(listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
                return false;
            }
            return true;
        }
    
    
    
     @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    
    
        if (requestCode == REQUEST_ID_MULTIPLE_PERMISSIONS) {
    
    
            if (grantResults.length > 0) {
                for (int i = 0; i < permissions.length; i++) {
    
    
                    if (permissions[i].equals(Manifest.permission.GET_ACCOUNTS)) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            Log.e("msg", "accounts granted");
    
                        }
                    } else if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            Log.e("msg", "storage granted");
    
                        }
                    } else if (permissions[i].equals(Manifest.permission.CALL_PHONE)) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            Log.e("msg", "call granted");
    
                        }
                    } else if (permissions[i].equals(Manifest.permission.RECEIVE_SMS)) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            Log.e("msg", "sms granted");
    
                        }
                    } else if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            Log.e("msg", "location granted");
    
                        }
                    }
    
    
                }
    
            }
    
    
        }
    }
    

    }

    0 讨论(0)
  • 2020-11-22 04:18

    In Kotlin:

    private val id = 1
    private val permissions = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.ACCESS_FINE_LOCATION)
    fun hasPermissions(): Boolean {
     for (perm in permissions) {
                    if (ActivityCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
                        return false
                    }
                }
    
            return true
        }
    
        if(! hasPermissions()){
                       requestPermissions(this, permissions, id)
               }
    
    0 讨论(0)
  • The following methodology is about

    • asking permissions dynamically ;
    • showing a AlertDialog if the user denies any permission
    • looping until the user accepts permission(s)

    Create a "static" class for permissions methods

    public class PermissionsUtil {
        public static final int PERMISSION_ALL = 1;
    
        public static boolean doesAppNeedPermissions(){
            return android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1;
        }
    
        public static String[] getPermissions(Context context)
                throws PackageManager.NameNotFoundException {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_PERMISSIONS);
    
            return info.requestedPermissions;
        }
    
        public static void askPermissions(Activity activity){
            if(doesAppNeedPermissions()) {
                try {
                    String[] permissions = getPermissions(activity);
    
                    if(!checkPermissions(activity, permissions)){
                        ActivityCompat.requestPermissions(activity, permissions,
                                PERMISSION_ALL);
                    }
                } catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }
    
        public static boolean checkPermissions(Context context, String... permissions){
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null &&
                    permissions != null) {
                for (String permission : permissions) {
                    if (ContextCompat.checkSelfPermission(context, permission) !=
                            PackageManager.PERMISSION_GRANTED) {
                        return false;
                    }
                }
            }
            return true;
        }
    }
    

    In MainActivity.java

        private void checkPermissions(){
            PermissionsUtil.askPermissions(this);
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode,
                                               @NonNull String[] permissions,
                                               @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            switch (requestCode) {
                case PermissionsUtil.PERMISSION_ALL: {
    
                    if (grantResults.length > 0) {
    
                        List<Integer> indexesOfPermissionsNeededToShow = new ArrayList<>();
    
                        for(int i = 0; i < permissions.length; ++i) {
                            if(ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {
                                indexesOfPermissionsNeededToShow.add(i);
                            }
                        }
    
                        int size = indexesOfPermissionsNeededToShow.size();
                        if(size != 0) {
                            int i = 0;
                            boolean isPermissionGranted = true;
    
                            while(i < size && isPermissionGranted) {
                                isPermissionGranted = grantResults[indexesOfPermissionsNeededToShow.get(i)]
                                        == PackageManager.PERMISSION_GRANTED;
                                i++;
                            }
    
                            if(!isPermissionGranted) {
    
                                showDialogNotCancelable("Permissions mandatory",
                                        "All the permissions are required for this app",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                checkPermissions();
                                            }
                                        });
                            }
                        }
                    }
                }
            }
        }
    
        private void showDialogNotCancelable(String title, String message,
                                             DialogInterface.OnClickListener okListener) {
            new AlertDialog.Builder(this)
                    .setTitle(title)
                    .setMessage(message)
                    .setPositiveButton("OK", okListener)
                    .setCancelable(false)
                    .create()
                    .show();
        }
    
    0 讨论(0)
提交回复
热议问题