棉花糖不会显示权限窗口

时间:2016-03-06 21:33:13

标签: android android-permissions android-6.0-marshmallow

我有一个应用,需要写日历现在被认为是“关键”所以我遵循指南HERE我在活动中添加了创建此cote

private static final int REQUEST_WRITE_CALENDAR = 1453;
  ...
boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED);
    if (!hasPermission) {
        ActivityCompat.requestPermissions(parentActivity,
                    new String[]{Manifest.permission.WRITE_CALENDAR},
                    REQUEST_WRITE_CALENDAR);
    }

但这并没有显示任何对话框。

此外,我似乎还应该使用此代码块来处理响应

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode)
    {
        case REQUEST_WRITE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                //reload my activity with permission granted or use the features what required the permission
            } else
            {
                Toast.makeText(parentActivity, "The app was not allowed to write to your calendar.", Toast.LENGTH_LONG).show();
            }
        }
    }

}

Android Target SDK是23并且是正确的。因此,问题的原因与可能的重复问题中提出的原因不同。

2 个答案:

答案 0 :(得分:1)

确定权限状态的逻辑可以简化为:

if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_CALENDAR) != PackageManager.PERMISSION_GRANTED) { 
    ActivityCompat.requestPermissions(parentActivity, 
                                      new String[]{Manifest.permission.WRITE_EXTERNAL_CALENDAR},
                                      REQUEST_WRITE_CALENDAR); 
}

您的Activity无需执行任何操作,覆盖onRequestPermissionsResult即可。

答案 1 :(得分:0)

问题的第二部分:

您可以在活动或片段中覆盖onRequestPermissionsResult。如果你选择在片段而不是活动中这样做,你应该在你的活动中添加这样的东西(为了将回调传递给你的片段):

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    for (Fragment frag : getSupportFragmentManager().getFragments()) {

        if (frag != null) {
                frag.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}