requestPermissions()没有

时间:2016-08-17 14:09:32

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

问题...

我尝试在Android Marshmallow中实现运行时权限,同时保持向后兼容性。我之前成功完成了这项工作,我不确定这次有什么不同。我已经在物理Note 5(运行Mallow)上测试了它,并使用在Marshmallow上设置的模拟器,但都不起作用。

我意识到"它没有工作"不是很有帮助,但我不知道还有什么可说的,没有任何反应。该应用程序不会崩溃,只是在调用requestPermissions(perms, 222)后挂起。

我做错了什么?

详细...

我活动的相关部分:

public class HomeActivity extends Activity implements View.OnClickListener {

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.btn_home_scancertificate:
                if (ContextCompat.checkSelfPermission(HomeActivity.this, "android.permission.CAMERA") != PackageManager.PERMISSION_GRANTED){
                    showNoPermDialog();
                }else {
                    AppData.ActionType = ActionType.SCAN_CERTIFICATE;
                    intent = new Intent(HomeActivity.this, CaptureActivity.class);
                    startActivity(intent);
                }
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        Log.e("HomeActivity", "Permissions results...");

        switch (requestCode) {
            case 222: {

                boolean granted = (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED);
                Log.e("HomeActivity", granted?"granted permission":"denied permission");

                AppData.ActionType = ActionType.SCAN_POSTCARD;
                intent = new Intent(HomeActivity.this, CaptureActivity.class);
                startActivity(intent);
            }
        }
    }

    public void getCamPerm(){
        Log.e("HomeActivity", "Build version: "+Build.VERSION.SDK_INT);
        if (Build.VERSION.SDK_INT >= 23) {
            Log.e("HomeActivity", "Getting permissions");

            String[] perms = new String[]{Manifest.permission.CAMERA};
            requestPermissions(perms, 222);
        }
    }

    public void showNoPermDialog(){
        if (Build.VERSION.SDK_INT >= 23) {
            boolean showRationale = shouldShowRequestPermissionRationale(Manifest.permission.CAMERA);

            String status = showRationale ? "showing rationale" : "skipping rationale";
            Log.e("HomeActivity", status);

            if (showRationale) {
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                alertDialogBuilder.setTitle("Need permission");
                alertDialogBuilder
                    .setMessage("App requires camera permission for the use of the scanner.")
                    .setCancelable(false)
                    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                            getCamPerm();
                        }
                    });
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }else getCamPerm();

        }else {

            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
            alertDialogBuilder.setTitle("Need permission");
            alertDialogBuilder
                    .setMessage("App requires permission to use the camera. You have disabled camera permission. Please re-enable this permission thru Settings -> Apps -> Our Town -> Permissions.")
                    .setCancelable(false)
                    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.show();
        }
    }

}

运行时,只会记录这些内容(根本不会调用onRequestPermissionsResult()

  

E / HomeActivity:跳过理由

     

E / HomeActivity:构建版本:23

     

E / HomeActivity:获取权限

清单包括:<uses-permission android:name="android.permission.CAMERA" />

修改

仅在我第一次点击按钮时,它会显示在Logcat中,似乎是通过调用shouldShowRequestPermissionRationale()

触发的
08-17 11:26:36.996 20660-20660/com.ourtownamerica.ourtowntrutrak W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=1035.6592, y[0]=770.2344, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=8508970, downTime=8506643, deviceId=0, source=0x1002 }
08-17 11:26:36.996 20660-20660/com.ourtownamerica.ourtowntrutrak W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=1035.6592, y[0]=770.2344, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=8508970, downTime=8506643, deviceId=0, source=0x1002 }
08-17 11:26:36.996 20660-20660/com.ourtownamerica.ourtowntrutrak W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=1035.6592, y[0]=770.2344, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=8508970, downTime=8506643, deviceId=0, source=0x1002 }
08-17 11:26:36.997 20660-20660/com.ourtownamerica.ourtowntrutrak W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=1035.6592, y[0]=770.2344, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=8508970, downTime=8506643, deviceId=0, source=0x1002 }

编辑2

我从它所在的Activity中复制了我原来的相同代码并将其移动到了splash活动中,并且在那里工作正常。它现在可以留在那里,但如果有人知道输入的内容仍然受到赞赏。

3 个答案:

答案 0 :(得分:0)

好吧,尝试使用Manifest.permission.CAMERA而不是&#34; android.permission.CAMERA&#34;

同样用于代码质量检查按钮单击本身是否为23或 R.id.btn_home_scancertificate:

if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(activity,
            Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {

        showNoPermDialog();

    } else {
        AppData.ActionType = ActionType.SCAN_CERTIFICATE;
                intent = new Intent(HomeActivity.this, CaptureActivity.class);
                startActivity(intent);
    }

    //in alertdialog button simply place this for requesting permission
    ActivityCompat.requestPermissions(activity,
            new String[]{Manifest.permission.CAMERA},
            222);

答案 1 :(得分:0)

对于M权限,我一直在使用this answer中的以下类:

public class MarshmallowPermission {
    public static final int EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2;
    public static final int CAMERA_PERMISSION_REQUEST_CODE = 3;

    public MarshmallowPermission() {
    }

    public boolean checkPermissionForExternalStorage(Activity activity) {
        if(Build.VERSION.SDK_INT >= 23) {
            int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if(result == PackageManager.PERMISSION_GRANTED) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    public boolean checkPermissionForCamera(Activity activity) {
        if(Build.VERSION.SDK_INT >= 23) {
            int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
            if(result == PackageManager.PERMISSION_GRANTED) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    public void requestPermissionForExternalStorage(Activity activity) {
        if(ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Toast.makeText(activity,
                    "External Storage permission needed. Please allow in App Settings for additional functionality.",
                    Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
        }
    }

    public void requestPermissionForCamera(Activity activity) {
        if(ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)) {
            Toast.makeText(activity,
                    "Camera permission needed. Please allow in App Settings for additional functionality.",
                    Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);
        }
    }
}

像这样工作:

        if(marshmallowPermission.checkPermissionForCamera(activity)) {
            // has camera
        } else {
            marshmallowPermission.requestPermissionForCamera(activity);
        }

并在Activity回调中处理

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    // handle request code
}

答案 2 :(得分:0)

问题很可能源于在要求获得许可之前致电shouldShowRequestPermissionRationale()。记录了一个针对此问题的错误(here),由于某些Google的示例/教程遵循此模式,因此它特别糟糕。

要解决此问题,请检查权限,如果尚未对其进行审核,请提出请求。在onRequestPermissionsResult()检查,看看你是否应该展示理由。如果用户拒绝了权限并且他们没有选择不再被要求的选项,则只会返回true

您可能会发现使用Andele库更容易使用此操作和推荐的UX准则。