//第一步 權限:
<uses-permission android:name="android.permission.CALL_PHONE" />
//Activity裡使用:
//撥号請求碼
public static final int REQUEST_CALL_PERMISSION = 10111;
//動态權限申請:
//打電話申請權限,
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;
}
//邏輯判斷,是否允許打電話權限
@Override
public 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;
}
}
//初始化:
//指定SIM卡撥打
public static final String[] dualSimTypes = { "subscription", "Subscription",
"com.android.phone.extra.slot",
"phone", "com.android.phone.DialingMode",
"simId", "simnum", "phone_type",
"simSlot" };
//打電話的方法: 0代表卡1,1代表卡2
//申請到權限後打電話
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);
Intent callIntent = new Intent(Intent.ACTION_CALL).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
callIntent.setData(Uri.parse(telPhone));
for (int i=0; i < dualSimTypes.length; i++) {
//0代表卡1,1代表卡2
callIntent.putExtra(dualSimTypes[i], 0);
}
this.startActivity(callIntent);
}
}
//在點選事件裡調用:
call("tel:" + "10086");
//----------------------------------------------------------完-----------------------------------------------------------------------