安卓 M 相机意图 + 权限错误?

我试图让我的应用程序为新的 Android M 权限变化做好准备,发现了一些奇怪的行为。我的应用程序使用了相机意图机制,允许用户从相机获得图片。但是在另一个活动中,需要使用相机本身并获得 Camera 许可(因为库依赖 card.io 需要这个许可)。

然而,当 M 在活动中只需要一个摄像头意图时,我尝试启动摄像头意图,我会看到以下崩溃(如果我从清单中删除摄像头权限,就不会发生这种情况) ,

> 09-25 21:57:55.260 774-8053/? I/ActivityManager: START u0
> {act=android.media.action.IMAGE_CAPTURE flg=0x3000003
> pkg=com.google.android.GoogleCamera
> cmp=com.google.android.GoogleCamera/com.android.camera.CaptureActivity
> (has clip) (has extras)} from uid 10098 on display 0 09-25
> 21:57:55.261 774-8053/? W/ActivityManager: Permission Denial: starting
> Intent { act=android.media.action.IMAGE_CAPTURE flg=0x3000003
> pkg=com.google.android.GoogleCamera
> cmp=com.google.android.GoogleCamera/com.android.camera.CaptureActivity
> (has clip) (has extras) } from null (pid=-1, uid=10098) with revoked
> permission android.permission.CAMERA 09-25 21:57:55.263 32657-32657/?
> E/ResolverActivity: Unable to launch as uid 10098 package
> com.example.me.mycamerselectapp, while running in android:ui 09-25
> 21:57:55.263 32657-32657/? E/ResolverActivity:
> java.lang.SecurityException: Permission Denial: starting Intent {
> act=android.media.action.IMAGE_CAPTURE flg=0x3000003
> pkg=com.google.android.GoogleCamera
> cmp=com.google.android.GoogleCamera/com.android.camera.CaptureActivity
> (has clip) (has extras) } from null (pid=-1, uid=10098) with revoked
> permission android.permission.CAMERA 09-25 21:57:55.263 32657-32657/?
> E/ResolverActivity:     at
> android.os.Parcel.readException(Parcel.java:1599) 09-25 21:57:55.263
> 32657-32657/? E/ResolverActivity:     at
> android.os.Parcel.readException(Parcel.java:1552) 09-25 21:57:55.263
> 32657-32657/? E/ResolverActivity:     at
> android.app.ActivityManagerProxy.startActivityAsCaller(ActivityManagerNative.java:2730)
> 09-25 21:57:55.263 32657-32657/? E/ResolverActivity:     at
> android.app.Instrumentation.execStartActivityAsCaller(Instrumentation.java:1725)
> 09-25 21:57:55.263 32657-32657/? E/ResolverActivity:     at
> android.app.Activity.startActivityAsCaller(Activity.java:4047) 09-25
> 21:57:55.263 32657-32657/? E/ResolverActivity:     at
> com.android.internal.app.ResolverActivity$DisplayResolveInfo.startAsCaller(ResolverActivity.java:983)
> 09-25 21:57:55.263 32657-32657/? E/ResolverActivity:     at
> com.android.internal.app.ResolverActivity.safelyStartActivity(ResolverActivity.java:772)
> 09-25 21:57:55.263 32657-32657/? E/ResolverActivity:     at
> com.android.internal.app.ResolverActivity.onTargetSelected(ResolverActivity.java:754)
> 09-25 21:57:55.263 32657-32657/? E/ResolverActivity:     at
> com.android.internal.app.ChooserActivity.onTargetSelected(ChooserActivity.java:305)
> 09-25 21:57:55.263 32657-32657/? E/ResolverActivity:     at
> com.android.internal.app.ResolverActivity.startSelected(ResolverActivity.java:603)
> 09-25 21:57:55.263 32657-32657/? E/ResolverActivity:     at
> com.android.internal.app.ChooserActivity.startSelected(ChooserActivity.java:310)
> 09-25 21:57:55.263 32657-32657/? E/ResolverActivity:     at
> com.android.internal.app.ChooserActivity$ChooserRowAdapter$2.onClick(ChooserActivity.java:990)
> 09-25 21:57:55.263 32657-32657/? E/ResolverActivity:     at
> android.view.View.performClick(View.java:5198) 09-25 21:57:55.263
> 32657-32657/? E/ResolverActivity:     at
> android.view.View$PerformClick.run(View.java:21147) 09-25 21:57:55.263
> 32657-32657/? E/ResolverActivity:     at
> android.os.Handler.handleCallback(Handler.java:739) 09-25 21:57:55.263
> 32657-32657/? E/ResolverActivity:     at
> android.os.Handler.dispatchMessage(Handler.java:95) 09-25 21:57:55.263
> 32657-32657/? E/ResolverActivity:     at
> android.os.Looper.loop(Looper.java:148) 09-25 21:57:55.263
> 32657-32657/? E/ResolverActivity:     at
> android.app.ActivityThread.main(ActivityThread.java:5417) 09-25
> 21:57:55.263 32657-32657/? E/ResolverActivity:     at
> java.lang.reflect.Method.invoke(Native Method) 09-25 21:57:55.263
> 32657-32657/? E/ResolverActivity:     at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
> 09-25 21:57:55.263 32657-32657/? E/ResolverActivity:     at
> com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 09-25
> 21:57:55.286 1159-1159/? I/Keyboard.Facilitator: onFinishInput() 09-25
> 21:57:55.297 32657-32676/? E/Surface: getSlotFromBufferLocked: unknown
> buffer: 0xaec352e0 09-25 21:57:55.344 325-349/? V/RenderScript:
> 0xb3693000 Launching thread(s), CPUs 4 09-25 21:57:57.290 325-349/?
> E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb3f88240

这是 Android M 已知的问题吗? 更重要的是,我该如何解决这个问题?

清单上有以下内容,

<uses-permission android:name="android.permission.CAMERA" />

这是我用来让用户用照相机点击图片和/或选择图片的代码

public static Intent openImageIntent(Context context, Uri cameraOutputFile) {


// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for(ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraOutputFile);
cameraIntents.add(intent);
}


// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);


// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Take or select pic");


// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
return chooserIntent;
}

我在我的活动中点击按钮来调用 openImageIntent()。当我没有在我的应用程序的 CAMERA 权限,它的工作很好,但添加了我得到的异常张贴在上面。

    @Override
public void onClick(View v) {
Intent picCaptureIntenet = openImageIntent(MainActivity.this, getTempImageFileUri(MainActivity.this));
try {
startActivityForResult(picCaptureIntenet, 100);
} catch(Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}

54923 次浏览

如果您正在使用 Android M 权限模型,那么您首先需要检查应用程序在运行时是否具有此权限,并且必须在运行时提示用户获得此权限。 在清单上定义的权限不会在安装时自动授予。

if (checkSelfPermission(Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {


requestPermissions(new String[]{Manifest.permission.CAMERA},
MY_REQUEST_CODE);
}

MY _ REQUEST _ CODE 是您可以定义的静态常量,它将再次用于 requestPermission 对话框回调。

您将需要一个对话框结果的回调:

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Now user should be able to use camera
}
else {
// Your app will not have this permission. Turn off all functions
// that require this permission or it will force close like your
// original question
}
}
}

编辑

从堆栈跟踪来看,Google CAMERA 似乎没有启用 CAMERA 权限。实际上,这看起来像是一个向后兼容的东西。

让我们假设 Google Camera (或任何其他处理 ACTION 意图的应用程序)需要一定的权限。

当你的应用程序没有 CAMERA 权限时,它只是让 Google CAMERA 使用旧的权限模型。

然而,通过在清单中声明的 CAMERA 权限,它也强制在 Google CAMERA (它没有 Android M 权限模型)中使用 Android M 权限模型(我认为)的 CAMERA 权限

这意味着使用上面的方法,你需要在运行时提供你的应用程序权限,这意味着它的子任务(在这个例子中是 Google Camera)现在也将拥有这个权限。

我也有同样的问题,然后在谷歌上找到了这个文档: Https://developer.android.com/reference/android/provider/mediastore.html#action_image_capture

注意: 如果应用程序的目标是 M 及以上,并声明使用未授予的 CAMERA 权限,则尝试使用此操作将导致 SecurityException

这太奇怪了。 完全说不通。 该应用程序使用 IMAGE _ CAPTURE 动作的意图声明 Camera 权限,刚刚运行到 SecurityException。但是如果您的应用程序没有声明使用意图和动作的 Camera 权限,IMAGE _ CAPTURE 可以毫无问题地启动 Camera 应用程序。

解决方法是检查应用程序是否有包含在清单中的摄像头权限,如果有,在启动意图之前请求摄像头权限。

以下是检查该权限是否包含在清单中的方法,与是否授予该权限无关。

public boolean hasPermissionInManifest(Context context, String permissionName) {
final String packageName = context.getPackageName();
try {
final PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
final String[] declaredPermisisons = packageInfo.requestedPermissions;
if (declaredPermisisons != null && declaredPermisisons.length > 0) {
for (String p : declaredPermisisons) {
if (p.equals(permissionName)) {
return true;
}
}
}
} catch (NameNotFoundException e) {


}
return false;
}

至于你的问题‘这在 M 中是一个已知的问题吗?’?一位谷歌开发人员回应说,有人报告这个问题是一个 bug。

看这里: Https://issuetracker.google.com/issues/37063818#comment8

以下是来自谷歌的消息: “这是为了避免用户失望的行为,他们撤销了应用程序的相机许可,应用程序仍然可以通过意图拍照。用户不知道在权限撤销后拍摄的照片是通过不同的机制发生的,并且会质疑权限模型的正确性。这适用于 MediaStore.ACTION _ IMAGE _ CAPTURE、 MediaStore.ACTION _ VIDEO _ CAPTURE 和 Inent.ACTION _ CALL 文档记录了针对 M 的应用程序行为变化的文档。”

既然 Google 不介意从用户那里抽象出使用相机的机制,那么你也可以战略性地触发第一个相机许可请求,并参考使用相机作为请求推理的活动的功能。如果你允许你的应用程序在用户只是想拍照的时候首先发出这个许可请求,用户可能会认为你的应用程序表现得很奇怪,因为拍照通常不需要授予许可。

如果您正在使用 Google M,请转到 设置-> 应用程序-> 你的应用程序-> 并给予适当的权限。

我删除了:

uses-permission android:name="android.permission.CAMERA"

而且只依靠:

uses-feature android:name="android.hardware.camera" android:required="true"

在清单文件中。

我在这个问题上卡住了,我已经在用 JTY 的答案了。问题在于,在某个时刻,请求权限对话框被选中为“永远不要再问”。我正在开发 SDK 24。

我的处理权限的完整代码如下:

public void checksCameraPermission(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Log.d("MyApp", "SDK >= 23");
if (this.checkSelfPermission(Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
Log.d("MyApp", "Request permission");
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MY_REQUEST_CODE);


if (! shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
showMessageOKCancel("You need to allow camera usage",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(FotoPerfil.this, new String[] {Manifest.permission.CAMERA},
MY_REQUEST_CODE);
}
});
}
}
else {
Log.d("MyApp", "Permission granted: taking pic");
takePicture();
}
}
else {
Log.d("MyApp", "Android < 6.0");
}
}

那么

private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}

然后

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_REQUEST_CODE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
criarFoto();
} else {
Toast.makeText(this, "You did not allow camera usage :(", Toast.LENGTH_SHORT).show();
noFotoTaken();
}
return;
}
}
}

预期的行为是,如果用户错误地选择了“永远不要再问”,您的应用程序会卡住(请求对话框没有显示) ,用户可能会感到沮丧。这样一个信息告诉他,他需要这个许可。

我的这个方法不检查只有相机,但所有的权限要求我的应用程序在启动... 我有这在我的 Helper.java 文件,另外注意,对于对话框,我使用这个库: https://github.com/afollestad/material-dialogs

  ///check camera permission
public static boolean hasPermissions(final Activity activity){


//add your permissions here
String[] AppPermissions = {
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};


//ungranted permissions
ArrayList<String> ungrantedPerms = new ArrayList<String>();
//loop


//lets set a boolean of hasUngrantedPerm to false
Boolean needsPermRequest = false;


//permissionGranted
int permGranted = PackageManager.PERMISSION_GRANTED;


//permission required content
String permRequestStr = activity.getString(R.string.the_following_perm_required);


//loop
for(String permission : AppPermissions){


//check if perm is granted
int checkPerm = ContextCompat.checkSelfPermission(activity,permission);


//if the permission is not granted
if(ContextCompat.checkSelfPermission(activity,permission) != permGranted){


needsPermRequest = true;


//add the permission to the ungranted permission list
ungrantedPerms.add(permission);


//permssion name
String[] splitPerm = permission.split(Pattern.quote("."));


String permName = splitPerm[splitPerm.length-1].concat("\n");


permRequestStr = permRequestStr.concat(permName);
}//end if


}//end loop




//if all permission is granted end exec
//then continue code exec
if(!needsPermRequest) {


return true;
}//end if


//convert array list to array string
final String[]  ungrantedPermsArray = ungrantedPerms.toArray(new String[ungrantedPerms.size()]);


//show alert Dialog requesting permission
new MaterialDialog.Builder(activity)
.title(R.string.permission_required)
.content(permRequestStr)
.positiveText(R.string.enable)
.negativeText(R.string.cancel)
.onPositive(new MaterialDialog.SingleButtonCallback(){
@Override
public void onClick(@NonNull MaterialDialog dialog,@NonNull DialogAction which){
//request the permission now
ActivityCompat.requestPermissions(activity,ungrantedPermsArray,0);
}
})
.show();


//return false so that code exec in that script will not be allowed
//to continue
return false;


}//end checkPermissions

因此,您可以在这里添加或删除您的权限列表:

//add your permissions here
String[] AppPermissions = {
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};

在我的活动 File 中,我像这样检查权限,Helper 类是我保存 hasPermission 方法的地方

 if(Helper.hasPermissions(this) == false){
return;
}//end if

意味着如果没有授权,我们不需要继续执行。 同样,我们需要在许可请求完成后侦听它,为此,将下面的代码添加到您的活动文件中(可选)

//Listen to Permission request completion
//put in your activity file
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
int permGranted = PackageManager.PERMISSION_GRANTED;


Boolean permissionRequired = false;


for(int perm : grantResults){


if(perm != permGranted){
permissionRequired = true;
}
}


//if permission is still required
if(permissionRequired){


//recheck and enforce permission again
Helper.hasPermissions(this);
}//end if


}//end method

有点晚了。但我还想补充一点。无论何时调用包含相机功能的方法,都要在 try catch 块中使用它。如果没有应用程序将崩溃的一些设备,如 MotoG4加或一加。

private static final int CAMERA_REQUEST_CODE = 10;
//TODO add camera opening functionality here.
try {
captureImage();
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent,CAMERA_REQUEST_CODE);
} catch (Exception e){
e.printStackTrace();
}


private void captureImage(){
if( ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.CAMERA},
CAMERA_REQUEST_CODE);
}
else {
// Open your camera here.
}
}
}


@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == CAMERA_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Now user should be able to use camera
}
else {
// Your app will not have this permission. Turn off all functions
// that require this permission or it will force close like your
// original question
}
}
}

注意: 确保不要复制粘贴覆盖的方法。

您必须为相机的使用启用应用程序权限。我更喜欢添加这个方法添加命令,激活相机:

    public static async Task<bool> HasPermission()
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera);
if (status == PermissionStatus.Granted) return true;


if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Camera))
{
ShowDialogOk("Error", "Please allow access to the camera.");//that is my custom method for allert
}


var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Camera);
status = results[Permission.Camera];


return status == PermissionStatus.Granted;
}