【注意事项】:
1、Android6.0以上系统运行时权限;
2、AndroidManifest.xml 中添加权限声明
3、运行时权限回调需要放在所属的Activity中,否则不会执行回调,参见博客;
<uses-permission android:name="android.permission.READ_PHONE_NUMBERS"/>
//指定SIM卡拨打
public static final String[] dualSimTypes = { "subscription", "Subscription",
"com.android.phone.extra.slot",
"phone", "com.android.phone.DialingMode",
"simId", "simnum", "phone_type",
"simSlot" };
//打电话
public void remoteCall(){
//拨打电话(Android6.0以上运行时权限)
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();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 1:
if(grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
call();
}else {
Toast.makeText(MainActivity.this,"You denied the permission",Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
//拨打电话,使用默认数据卡
public static void call(){
try{
TelecomManager telecomManager = (TelecomManager) getContext().getSystemService(Context.TELECOM_SERVICE);
if(telecomManager != null){
Intent intent = new Intent(Intent.ACTION_CALL);
String number = (String) SharedPreferencesUtil.getParam(getContext(),"monitorphone","");
intent.setData(Uri.parse("tel:"+number));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
for (int i=0; i < dualSimTypes.length; i++) {
//1代表卡1,2代表卡2
intent.putExtra(dualSimTypes[i], 1);
}
getContext().startActivity(intent);
}
}catch (SecurityException e){
e.printStackTrace();
}
}
发短信的权限申请类似打电话,不贴代码了,主要使用SmsManager类的sendTextMessage方法,同时要声明权限:
<uses-permission android:name="android.permission.SEND_SMS"/>
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number, null, message, null, null);
【短信发送试验测试】:
【遗留问题】:选择指定手机卡发送短信该怎么办?SmsManager 类实现的发短信,双卡情况下默认选择1卡,有没有其他的办法实现,求路过的兄弟留言指点,多谢!