gpt4 book ai didi

android - 如何在 Android 中询问相机的运行时权限,运行时存储权限

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:33:48 24 4
gpt4 key购买 nike

我正在开发一个通过单击按钮扫描条形码的应用程序,它在 Lollipop 版本上运行良好。当我来到 Marshmallow 时,它停止工作了。这是错误:

camerabase an error occurred while connecting to camera 0

它迫使我通过以下方式打开权限:

设置 --> 应用程序 --> 我的应用程序 --> 相机。

我的问题是如何在 Marshmallow 中或通过要求用户在运行时打开相机来自动允许我的应用程序获得相机权限。屏幕截图:

enter image description here

最佳答案

下面我写了一段代码,用于为相机授予运行时权限,有一个字符串数组,您可以在其中根据需要在运行时授予多个请求。

public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 200;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkPermission()) {
//main logic or main code

// . write your main code to execute, It will execute if the permission is already given.

} else {
requestPermission();
}
}

private boolean checkPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
return false;
}
return true;
}

private void requestPermission() {

ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
PERMISSION_REQUEST_CODE);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_SHORT).show();

// main logic
} else {
Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
showMessageOKCancel("You need to allow access permissions",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermission();
}
}
});
}
}
}
break;
}
}

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

关于android - 如何在 Android 中询问相机的运行时权限,运行时存储权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42275906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com