简体   繁体   中英

Android multiple runtime permission in single dialog

I am trying to get all permission in a single dialog file and I followed the below link which provided me with an example http://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en

This is my code

public class MActivity extends AppCompatActivity {

final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;

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

    insertDummyContactWrapper();

}

@TargetApi(Build.VERSION_CODES.M)
private void insertDummyContactWrapper() {
    List<String> permissionsNeeded = new ArrayList<String>();

    final List<String> permissionsList = new ArrayList<String>();
    if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
        permissionsNeeded.add("GPS");
    if (!addPermission(permissionsList, Manifest.permission.READ_CONTACTS))
        permissionsNeeded.add("Read Contacts");
    if (!addPermission(permissionsList, Manifest.permission.WRITE_CONTACTS))
        permissionsNeeded.add("Write Contacts");

    if (permissionsList.size() > 0) {
        if (permissionsNeeded.size() > 0) {
            // Need Rationale
            String message = "You need to grant access to " + permissionsNeeded.get(0);
            for (int i = 1; i < permissionsNeeded.size(); i++)
                message = message + ", " + permissionsNeeded.get(i);
            showMessageOKCancel(message,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                    REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                        }
                    });
            return;
        }
        requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
        return;
    }

    insertDummyContact();
}

@TargetApi(Build.VERSION_CODES.M)
private boolean addPermission(List<String> permissionsList, String permission) {
    if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
        permissionsList.add(permission);
        // Check for Rationale Option
        if (!shouldShowRequestPermissionRationale(permission))
            return false;
    }
    return true;
}


private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {

    new AlertDialog.Builder(MActivity.this)
            .setMessage(message)
            .setPositiveButton("OK", okListener)
            .setNegativeButton("Cancel", null)
            .create()
            .show();
}

private static final String TAG = "Contacts";

private void insertDummyContact() {

    // Two operations are needed to insert a new contact.
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(2);

    // First, set up a new raw contact.
    ContentProviderOperation.Builder op =
            ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null);
    operations.add(op.build());

    // Next, set the name for the contact.
    op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
            .withValue(ContactsContract.Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                    "__DUMMY CONTACT from runtime permissions sample");
    operations.add(op.build());

    // Apply the operations.
    ContentResolver resolver = getContentResolver();
    try {
        resolver.applyBatch(ContactsContract.AUTHORITY, operations);
    } catch (RemoteException e) {
        Log.d(TAG, "Could not add a new contact: " + e.getMessage());
    } catch (OperationApplicationException e) {
        Log.d(TAG, "Could not add a new contact: " + e.getMessage());
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
            Map<String, Integer> perms = new HashMap<String, Integer>();
            // Initial

            perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.READ_CONTACTS, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.WRITE_CONTACTS, PackageManager.PERMISSION_GRANTED);
            // Fill with results

            for (int i = 0; i < permissions.length; i++)
                perms.put(permissions[i], grantResults[i]);

          ;
            // Check for ACCESS_FINE_LOCATION
            if (perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    && perms.get(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED
                    && perms.get(Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
                // All Permissions Granted

                insertDummyContact();
            } else {
                // Permission Denied

                Toast.makeText(MActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
                        .show();
            }
        }
        break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
}

I got the dialog box which asked for the permission and after given ok I checked the setting-->apps-->myappname-->permission, but permission was not set ?

Can some one please help me in this matter.

When I added permission in my mainfest file it worked perfectly. Note : But I did anotherway

public class RecursionActivity extends AppCompatActivity {
Context context;
private static final int PERMISSION_REQUEST_CODE = 1;
String p1 = android.Manifest.permission.READ_CONTACTS, p2 = android.Manifest.permission.ACCESS_FINE_LOCATION,
        p3 = android.Manifest.permission.WRITE_CONTACTS, p4 = Manifest.permission.CAMERA;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;
    setContentView(R.layout.activity_recursion);
    permissionAccess();
}


private void permissionAccess() {


    if (!checkPermission(p1)) {
        Log.e("TAG",p1);
        requestPermission(p1);
    } else if (!checkPermission(p2)) {
        Log.e("TAG",p2);
        requestPermission(p2);
    } else if (!checkPermission(p3)) {
        Log.e("TAG",p3);
        requestPermission(p3);
    } else if (!checkPermission(p4)) {
        Log.e("TAG",p4);
        requestPermission(p4);
    } else {
        Toast.makeText(context, "All permission granted", Toast.LENGTH_LONG).show();
    }


}

private boolean checkPermission(String permission) {
    int result = ContextCompat.checkSelfPermission(context, permission);
    if (result == PackageManager.PERMISSION_GRANTED) {
        return true;
    } else {
        return false;
    }
}

private void requestPermission(String permission) {

    if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(RecursionActivity.this, new String[]{permission}, PERMISSION_REQUEST_CODE);
    } else {
        //Do the stuff that requires permission...
        Log.e("TAG","Not say request");
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE:
            Log.e("TAG", "val " + grantResults[0]);
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                permissionAccess();
            } else {
                Toast.makeText(context, "Bye bye", Toast.LENGTH_LONG).show();
            }
            break;
    }
}
}

I don't know whether this is an optimized solution or not but I hope it will be helpful for someone.

addPermission方法中添加所需的权限,如下所示:

ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_PHONE_STATE,android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_COARSE_LOCATION}, 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM