Android双卡打电话和发短信

绿豆饼 2019-11-01

一、打电话

首先需要申请电话信息权限,AndroidManifest.xml权限配置如下所示。

1 <!-- 打电话的权限 -->
2     <uses-permission android:name="android.permission.CALL_PHONE"/>
3     <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Android5.1及以前版本只需要在AndroidManifest.xml中配置完权限后就可以进行打电话,打电话方式如下:

Intent intent = new Intent(Intent.ACTION_CALL);//android.intent.action.CALL
 //2). 携带数据
 String number = et_main_number.getText().toString();
 intent.setData(Uri.parse("tel:"+number));
 //3). startActivity(intent)
 startActivity(intent);

对于Android5.1以后的版本,除了AndroidManifest.xml权限配置以外,还需要通过用户允许获取权限,代码如下所示:

//检测用户是否同意权限
    private void checkPermission(int id) {
        //判断所申请的权限是不是已经通过,没通过返回false,通过返回true,则提示出来并拨打电话
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            //申请权限回调函数
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSION_REQUEST_CODE);
        } else {
            Toast.makeText(this, "权限已被申请通过咯!", Toast.LENGTH_SHORT).show();
            call(id);
        }
    }

 //权限申请回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case PERMISSION_REQUEST_CODE:
                //同意申请的权限
                if (grantResults.length>0&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(this,"同意通过",Toast.LENGTH_SHORT).show();
//                    call();
                    //拒绝申请的权限
                }else{
                    Toast.makeText(this,"拒绝通过",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }

    }

获取到电话权限后,可以使用以下代码进行双卡选择打电话,id为0表示卡一,id为1表示卡二,适用于Android5.1以后的方法,代码如下:

package com.example.phone;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telecom.PhoneAccountHandle;
import android.telecom.TelecomManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends Activity {

    private static final int PERMISSION_REQUEST_CODE = 1;
    private EditText et_main_number;
    private Button btn_main_call1;
    private Button btn_main_call2;
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(v==btn_main_call1){
                checkPermission(0);
            }
            else if(v==btn_main_call2){
                checkPermission(1);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化视图对象
        et_main_number = (EditText) findViewById(R.id.et_main_number);
        btn_main_call1 = (Button) findViewById(R.id.btn_main_call1);
        btn_main_call2 = (Button) findViewById(R.id.btn_main_call2);
        //给视图对象设置点击监听
        btn_main_call1.setOnClickListener(onClickListener);
        btn_main_call2.setOnClickListener(onClickListener);
    }

    //检测用户是否同意权限
    private void checkPermission(int id) {
        //判断所申请的权限是不是已经通过,没通过返回false,通过返回true,则提示出来并拨打电话
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            //申请权限回调函数
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSION_REQUEST_CODE);
        } else {
            Toast.makeText(this, "权限已被申请通过咯!", Toast.LENGTH_SHORT).show();
            call(id);
        }
    }

    private void call(int id) {
        Intent intent = new Intent(Intent.ACTION_CALL).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//android.intent.action.CALL
        //2). 携带数据
        String number = et_main_number.getText().toString();
        intent.setData(Uri.parse("tel:" + number));

        TelecomManager telecomManager = (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        List<PhoneAccountHandle> phoneAccountHandleList = telecomManager.getCallCapablePhoneAccounts();
        intent.putExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE,phoneAccountHandleList.get(id));
        //3). startActivity(intent)
        startActivity(intent);
    }
    //权限申请回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case PERMISSION_REQUEST_CODE:
                //同意申请的权限
                if (grantResults.length>0&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(this,"同意通过",Toast.LENGTH_SHORT).show();
//                    call();
                    //拒绝申请的权限
                }else{
                    Toast.makeText(this,"拒绝通过",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }

    }
}

activity_main.xml代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="电话号码: " />
        <EditText
            android:id="@+id/et_main_number"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:hint="请输入号码">
        </EditText>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/btn_main_call1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="卡1" />
        <Button
            android:id="@+id/btn_main_call2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="卡2" />
    </LinearLayout>
</LinearLayout>

完成以上操作,即可实现双卡选择打电话。

二、发短信

首先需要申请电话信息权限,AndroidManifest.xml权限配置如下所示。

1 <!-- 发短信的权限 -->
2     <uses-permission android:name="android.permission.SEND_SMS"/>

除了AndroidManifest.xml权限配置以外,还需要通过用户允许获取权限,代码如下所示:

//检测用户是否同意权限
    private void checkPermission(int id) {
        //判断所申请的权限是不是已经通过,没通过返回false,通过返回true,则提示出来并发送短信
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
            //申请权限回调函数
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, PERMISSION_REQUEST_CODE);
        } else {
            Toast.makeText(this, "权限已被申请通过咯!", Toast.LENGTH_SHORT).show();
            message(id);
        }
    }

//权限申请回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case PERMISSION_REQUEST_CODE:
                //同意申请的权限
                if (grantResults.length>0&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(this,"同意通过",Toast.LENGTH_SHORT).show();
                    //拒绝申请的权限
                }else{
                    Toast.makeText(this,"拒绝通过",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }

    }

获取到短信权限后,可以使用以下代码进行双卡选择打电话,id为0表示卡一,id为1表示卡二,代码如下:

package com.example.message;

import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.SmsManager;
import android.telephony.SubscriptionManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MainActivity extends Activity{

    private static final int PERMISSION_REQUEST_CODE = 1;
    private EditText et_main_number;
    private EditText et_main_sms;
    private Button btn_main_send;

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(v==btn_main_send) {
                //id=0为卡一,id=1为卡二
                checkPermission(0);
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化视图对象
        et_main_number = (EditText) findViewById(R.id.et_main_number);
        et_main_sms = findViewById(R.id.et_main_sms);
        btn_main_send = (Button) findViewById(R.id.btn_main_send);
        //给视图对象设置点击监听
        btn_main_send.setOnClickListener(onClickListener);
    }

    //检测用户是否同意权限
    private void checkPermission(int id) {
        //判断所申请的权限是不是已经通过,没通过返回false,通过返回true,则提示出来并拨打电话
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
            //申请权限回调函数
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, PERMISSION_REQUEST_CODE);
        } else {
            Toast.makeText(this, "权限已被申请通过咯!", Toast.LENGTH_SHORT).show();
            message(id);
        }
    }
    private void message(int id) {
        SubscriptionManager smanager = (SubscriptionManager) getSystemService(TELEPHONY_SUBSCRIPTION_SERVICE);
        Class sclazz = smanager.getClass();
        Method getSubId = null;
        try {
            getSubId = sclazz.getDeclaredMethod("getSubId",int.class);
        }catch (NoSuchMethodException e){
            e.printStackTrace();
        }
        int[] ints = new int[1];
        try {
            ints = (int[])getSubId.invoke(smanager,id);
        }catch (IllegalAccessException e){
            e.printStackTrace();
        }catch (InvocationTargetException e){
            e.printStackTrace();
        }
        SmsManager smsManager = SmsManager.getSmsManagerForSubscriptionId(ints[0]);
        PendingIntent sentIntent = PendingIntent.getBroadcast(this,0, new Intent(Context.TELEPHONY_SUBSCRIPTION_SERVICE),PendingIntent.FLAG_ONE_SHOT);
        String number = et_main_number.getText().toString();
        String sms = et_main_sms.getText().toString();
        smsManager.sendTextMessage(number,null,sms,sentIntent,null);
    }
    //权限申请回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case PERMISSION_REQUEST_CODE:
                //同意申请的权限
                if (grantResults.length>0&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(this,"同意通过",Toast.LENGTH_SHORT).show();
                    //拒绝申请的权限
                }else{
                    Toast.makeText(this,"拒绝通过",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }

    }
}

activity_main.xml代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="电话号码: " />
        <EditText
            android:id="@+id/et_main_number"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="请输入号码">
        </EditText>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="短信内容: " />
        <EditText
            android:id="@+id/et_main_sms"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="请输入短信">
        </EditText>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <Button
            android:id="@+id/btn_main_send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="发短信" />
    </LinearLayout>

</LinearLayout>

完成以上操作后,即可实现双卡选择发送短信。

相关推荐