Android 权限请求代码问题 [英] Android Permission Request Code Issue

查看:34
本文介绍了Android 权限请求代码问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何请求权限?我尝试记录文档,但常量 int 请求代码 MY_PERMISSIONS_REQUEST_CALL_PHONE 似乎不起作用,为了向后兼容性还有什么要记住的吗?

How to request a Permission? I tried to documentation, but the constant int request code MY_PERMISSIONS_REQUEST_CALL_PHONE donst seem to just work, anything else to bear in mind for Backwards compatibility?

ActivityCompat.requestPermissions(getApplicationContext(),
                            new String[]{Manifest.permission.READ_CONTACTS},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE);

如何声明 MY_PERMISSIONS_REQUEST_CALL_PHONE 常量 int?

How to declare MY_PERMISSIONS_REQUEST_CALL_PHONE constant int?

推荐答案

对于低版本你只需要在 manifest 中声明权限,但是对于 marshmellow,您需要在代码中提供它,您要在其中执行代码.

For lower versions you need to declare permission in manifest only, but for marshmellow you need to give it in the code, where you want to execute the code.

在这里,您要拨打电话.因此,在为进行调用而编写的代码块中插入/包含下面提供的代码.

Here, you want to make a call. So, insert/include the code provided below in the code block written to make the call.

   public void makeCall(){
       Intent intent = new Intent(Intent.ACTION_CALL);
       intent.setData(Uri.parse("tel:" + "123456"));
       int result = ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE);
       if (result == PackageManager.PERMISSION_GRANTED){
           startActivity(intent);
       } else {
           requestForCallPermission(); 
       }
  }

  private void requestPermission(){
    if(ActivityCompat.shouldShowRequestPermissionRationale(activity,Manifest.permission.CALL_PHONE)){} 
    else {
           ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.CALL_PHONE},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) { 
                makeCall(); 
            } 
            break;
      }
  }

这篇关于Android 权限请求代码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆