4.4

所花时间(包括上课):3

打码量(行):400

博客量(篇):1

了解到知识点:学习运行时动态申请权限Lazy模式

 

 import android.Manifest;

import android.content.pm.PackageManager;

import android.os.Bundle;

import android.util.Log;

import androidx.annotation.NonNull;

import androidx.appcompat.app.AppCompatActivity;

import androidx.core.app.ActivityCompat;

import androidx.core.content.ContextCompat;

 

public class MainActivity extends AppCompatActivity {

 

    private static final String TAG = "MainActivity";

    private static final int CAMERA_PERMISSION_REQUEST_CODE = 100;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        // 示例:检查和申请相机权限

        if (checkCameraPermission()) {

            // 已授予相机权限,执行相机相关操作

            Log.d(TAG, "Camera permission granted.");

            openCamera();

        } else {

            // 未授予相机权限,请求权限

            requestCameraPermission();

        }

    }

 

    private boolean checkCameraPermission() {

        // 检查相机权限是否已授予

        return ContextCompat.checkSelfPermission(this,

                Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;

    }

 

    private void requestCameraPermission() {

        // 请求相机权限

        ActivityCompat.requestPermissions(this,

                new String[]{Manifest.permission.CAMERA},

                CAMERA_PERMISSION_REQUEST_CODE);

    }

 

    private void openCamera() {

        // 打开相机,执行相机相关操作

        Log.d(TAG, "Opening camera...");

        // 在这里可以执行需要相机权限的操作

    }

 

    @Override

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // 用户授予了相机权限,执行相机相关操作

                Log.d(TAG, "Camera permission granted after request.");

                openCamera();

            } else {

                // 用户拒绝了相机权限,可以给出提示或者进行其他处理

                Log.d(TAG, "Camera permission denied.");

            }

        }

    }

}

posted @ 2024-04-04 13:56  赵千万  阅读(7)  评论(0编辑  收藏  举报