其他分享
首页 > 其他分享> > Android在单个对话框中具有多个运行时权限

Android在单个对话框中具有多个运行时权限

作者:互联网

我试图在一个对话框文件中获得所有许可,然后单击下面的链接为我提供了一个示例
http://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en

这是我的代码

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);
    }
}
}

我得到了询问许可的对话框,在确定后,我检查了设置-> apps-> myappname->许可,但未设置许可?

有人能在这件事上帮助我吗?

解决方法:

当我在mainfest文件中添加权限时,它可以很好地工作.
注意:但是我还是改了

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;
    }
}
}

我不知道这是否是一个优化的解决方案,但我希望它对某人有帮助.

标签:android-permissions,android-6-0-marshmallow,runtime-permissions,android
来源: https://codeday.me/bug/20191118/2030987.html