在程序运行时申请限权(CALL_PHONE),CALL_PHONE这个限权是编写拨打电话功能的时候需要声明的,安卓6.0之后的,实现,在布局文件中添加
<uses-permission android:name="android.permission.CALL_PHONE"/>声明其限权
之后在MainActivity.class中添加代码
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Button makeCall =(Button)findViewById(R.id.make_call); makeCall.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest. permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.CALL_PHONE},1); }else{ call(); } } }); }
checkSelfPermission()方法接受两个参数,一个是context,另一个参数是接受的限权名,打电话的限权名是Manifest.permission.CALL_PHONE,然后我们使用方法的返回值和PackageManager.GRANETED进行比较,相等说明授权了,不相等就表示用户没有授权
private void cal(){ try{ Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:10086")); startActivity(intent); }catch(SecurityEXception e){ e.printStackTrace(); } }
call()方法
@Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){ switch(requestCode){ case 1: if(grantResults.length >0 && grantResults[0] == PackageManager .PERMISSION_GRANTED){ call(); }else{ Toast.makeText(this,"You denied the permission",Toast.LENGTH_SHORT).show(); } break; default: } }
用户允许该线圈,上面的requesCode是请求码,permission是申请的限权,grantResults是请求的结果.
原文:https://www.cnblogs.com/p-t-m/p/12927107.html