Android在活动开始时询问相机权限

时间:2018-04-24 13:21:44

标签: java android android-camera android-permissions

我需要请求相机许可,但不知怎的,我无法管理它。

我有以下函数,我在onCreate方法中调用:

public void checkCameraPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSION_CAMERA);
    }
}

但是Android Studio给了我这条消息Cannot resolve Symbol CAMERA

我没有事件开始渐变。

在我的清单文件中,我有以下权限:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

<uses-feature android:name="android.hardware.camera2" />
<uses-feature android:name="android.hardware.camera.any" android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
<uses-feature android:name="android.hardware.camera.flash" android:required="false" />
<uses-feature android:name="android.hardware.microphone" android:required="false" />

知道如何以编程方式正确地请求权限吗?

我的Build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '24.0.0'
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId 'com.foo.var
        minSdkVersion 22
        targetSdkVersion 22
        versionCode 5
        versionName "1.2"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }


    compileOptions {
        targetCompatibility 1.8
        sourceCompatibility 1.8
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:24.1.1'
    compile 'com.android.support:support-v4:24.1.1'

    compile 'com.github.GrenderG:Toasty:1.2.5' // Toasty Class
    compile 'com.jakewharton:butterknife:8.1.0'//Butterknife
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.1.0'
    compile 'com.squareup.retrofit2:retrofit:2.3.0' // REST Call
    compile 'com.squareup.retrofit2:converter-moshi:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0' // JSON Converter für Retrofit
    compile 'com.basgeekball:awesome-validation:2.0' 
    compile 'com.github.apl-devs:appintro:v4.2.2' // AppIntro
    compile 'com.github.KyleBanks:animated-line-graph-view:v1.0.1'

    // constraint layout
    compile 'com.android.support.constraint:constraint-layout:1.0.2'

    // from webrtc sample ...
    // compile 'com.pubnub:pubnub-android:3.7.4'
    compile group: 'com.pubnub', name: 'pubnub-gson', version: '4.18.0'
    compile 'io.pristine:libjingle:9694@aar'
    compile project(':pnwebrtc')
}

3 个答案:

答案 0 :(得分:1)

尝试这两种方法..

    private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
   /**
 * this method check permission and return current state of permission need.
 */
private boolean checkPermissions() {
    int permissionState = ActivityCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA);
    return permissionState == PackageManager.PERMISSION_GRANTED;
}

/**
 * this method request to permission asked.
 */
private void requestPermissions() {
    boolean shouldProvideRationale =
            ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CAMERA);

    if (shouldProvideRationale) {
        Log.i(TAG, "Displaying permission rationale to provide additional context.");
           } else {
        Log.i(TAG, "Requesting permission");
        // previously and checked "Never ask again".
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                REQUEST_PERMISSIONS_REQUEST_CODE);
    }
}

然后当这样检查..

  if (!checkPermissions()) {
        requestPermissions();
    }

这个变量REQUEST_PERMISSIONS_REQUEST_CODE访问onResult方法,如下面的代码..

/**
 * Callback received when a permissions request has been completed.
 */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    Log.i(TAG, "onRequestPermissionResult");
    if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
        if (grantResults.length <= 0) {
            // If user interaction was interrupted, the permission request is cancelled and you
            // receive empty arrays.
            Log.i(TAG, "User interaction was cancelled.");
        } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission was granted. Kick off the process of building and connecting
            // GoogleApiClient.
            // perform your operation
        } else {
            // Permission denied.
        }
    }
}

答案 1 :(得分:1)

尝试使用以下语句导入: -

import android.Manifest;

您可以尝试这种方式 - 用以下代码替换您的代码: -

 int permissionCheck = Context.checkSelfPermission(getActivity(),
                        Manifest.permission.CAMERA);
                if (permissionCheck== PackageManager.PERMISSION_DENIED) {
                    requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_WRITE_STORAGE);
                }

答案 2 :(得分:0)

我建议使用RxPermission Library。这就是代码的样子。

RxPermissions rxPermissions = new RxPermissions(this); 
rxPermissions
    .request(Manifest.permission.CAMERA)
    .subscribe(granted -> {
        if (granted) { // Always true pre-M
           // I can control the camera now
        } else {
           // Oups permission denied
        }
    });

这看起来不是很干净而且很短! :)

Gradle Dependency

dependencies {
    compile 'com.tbruyelle.rxpermissions2:rxpermissions:0.9.5@aar'
}