1.在清单文件加入权限。
<uses-permissionandroid:name="android.permission.CALL_PHONE"/>
2.在Activity中申请权限。
public static final int REQUEST_CALL_PERMISSION = 10111; //拨号请求码/*** 判断是否有某项权限* @param string_permission 权限* @param request_code 请求码* @return*/public boolean checkReadPermission(String string_permission,int request_code) {boolean flag = false;if (ContextCompat.checkSelfPermission(this, string_permission) == PackageManager.PERMISSION_GRANTED) {//已有权限flag = true;} else {//申请权限ActivityCompat.requestPermissions(this, new String[]{string_permission}, request_code);}return flag;}/*** 检查权限后的回调* @param requestCode 请求码* @param permissions 权限* @param grantResults 结果*/@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {switch (requestCode) {case REQUEST_CALL_PERMISSION: //拨打电话if (permissions.length != 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {//失败Toast.makeText(this,"请允许拨号权限后再试",Toast.LENGTH_SHORT).show();} else {//成功call("tel:"+"10086");}break;}}/*** 拨打电话(直接拨打)* @param telPhone 电话*/public void call(String telPhone){if(checkReadPermission(Manifest.permission.CALL_PHONE,REQUEST_CALL_PERMISSION)){Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse(telPhone));startActivity(intent);}}
3.最后调用call()函数。
//在需要的地方直接调用call()方法:call("tel:"+phone);
拓展知识:Android拨打电话的几种方式方式。
1.直接拨打电话。
Intent Intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:" + phoneNumber));
startActivity(Intent);
2.Android跳转到拨号界面。
Intent Intent = new Intent(Intent.ACTION_CALL_BUTTON);//跳转到拨号界面
startActivity(Intent);
3.Android跳转到拨号界面,同时传递电话号码。
Intent Intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:" + phoneNumber));
startActivity(Intent);