我正在做一个按钮点击扫描条形码的应用程序,它可以正常工作到Lollipop版本.当我来到棉花糖时,它停止了工作.这是错误:
camerabase an error occurred while connecting to camera 0
它迫使我通过以下方式开启许可:
设置 – >申请 – >我的应用 – >相机.
我的问题是如何在Marshmallow中自动允许我的应用程序使用相机,或者要求用户在运行时打开相机.屏幕截图:
解决方法:
下面我编写了一个代码,用于授予Camera的运行时权限.有一个String of Array,你可以在其中给出多个请求,这些请求在运行时需要.
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 – 如何询问Camera的运行时权限全部内容,希望文章能够帮你解决android – 如何询问Camera的运行时权限所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)