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

查看:97
本文介绍了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?

推荐答案

对于较低版本,您只需要在清单中声明许可, 但是对于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天全站免登陆