Android 6 camera.open()异常解决方法

最近需要在Android平台写一个处理视频帧的Demo,于是在网上下了很多的Demo代码,奇怪的是下载的很多通过Camera提取视频帧的程序在Android Studio中都能通过编译,但是每次一放到真机上一测试程序就闪退崩掉了。
我的开发环境为Android Studio 2.1,编译时的SDK选的是API 23,测试机为华为P9。

网上搜了很多资料说要在AndroidManifest文件中添加访问Camera的权限,然而我添加之后依然没有解决。这个问题折腾了我快一周,后面我才发现是权限的问题。我的测试机华为P9是Android 6的系统,而Android系统从6.0版本开始增加了一种运行时权限,Camera正好属于运行时权限,这种权限的授权不像6.0以前的Android系统可以安装APP的时候就一次性授权。综上,最后找到了程序在华为P9上一测试就崩掉的原因:程序在运行中请求camera.open()时实际上程序并未获得操作Camera的权限,所以camera.open()会一直打开失败。

问题找到了,怎么解决呐?下面介绍方法有两种。

方法一:修改编译的SDK,在src下的build.gradle中把编译的SDK改为低于23版本的SDK(因为Android 6系统对应的最低SDK版本号为API level 23)。下面是一个示例。

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "org.mogujie.guigu.camerademo"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:22.0.0'
}

方法二:在Java代码中添加运行时权限授权。方法:在需要用Camera的地方添加授权代码,如在Mainactivity的onCreate函数中添加如下代码。

  // check Android 6 permission
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED) {
            Log.i("TEST","Granted");
            //init(barcodeScannerView, getIntent(), null);
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA}, 1);//1 can be another integer
        }

除此,由于以上代码来自其它包,因此还需要import下面的这些包

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;

Reference:
http://www.open-open.com/lib/view/open1450578678148.html
https://github.com/open-keychain/open-keychain/blob/master/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/QrCodeCaptureActivity.java

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值