在您的
onClick()方法中尝试此代码
if(isPermissionGranted()){ call_action();}现在,调用创建一个单独的方法:
public void call_action(){ String phnum = etPhoneno.getText().toString(); Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:" + phnum)); startActivity(callIntent); }添加以下两种用于运行时权限检查的方法:
public boolean isPermissionGranted() { if (Build.VERSION.SDK_INT >= 23) { if (checkSelfPermission(android.Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) { Log.v("TAG","Permission is granted"); return true; } else { Log.v("TAG","Permission is revoked"); ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 1); return false; } } else { //permission is automatically granted on sdk<23 upon installation Log.v("TAG","Permission is granted"); return true; }} @Overridepublic void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case 1: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show(); call_action(); } else { Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show(); } return; } // other 'case' lines to check for other // permissions this app might request } }还要确保将其添加到清单中:
<uses-permission android:name="android.permission.CALL_PHONE" />
碎片
如果您在中尝试使用此代码 fragment
,请更改
checkSelfPermission()
至
ActivityCompat.checkSelfPermission()
并且也改变
ActivityCompat.requestPermissions()
至
requestPermissions()



