Android13 获取双卡信号强度

发布时间:2024年01月13日

1、添加工具类

package com.example.utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.CellSignalStrength;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;

import androidx.core.app.ActivityCompat;

import java.lang.reflect.Field;
import java.util.List;

/**
 * author :
 * Creation Date : 2023/1/10
 * description :
 */
public class PhoneUtils {

    public static int NETWORK_TYPE_NONE = 0;
    public static int NETWORK_TYPE_WIFI = 1;
    public static int NETWORK_TYPE_4G = 2;
    public static int NETWORK_TYPE_2G = 3;

    /**
     * 判断是否包含SIM卡
     *
     * @return 状态
     */
    public static boolean hasSimCard(Context context) {
        TelephonyManager telMgr = (TelephonyManager)
                context.getSystemService(Context.TELEPHONY_SERVICE);
        int simState = telMgr.getSimState();
        boolean result = true;
        switch (simState) {
            case TelephonyManager.SIM_STATE_ABSENT:
            case TelephonyManager.SIM_STATE_UNKNOWN:
                result = false; // 没有SIM卡
                break;
        }
        return result;
    }

    public static int getNetWorkType(Context context) {
        int mNetWorkType = -1;
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            String type = networkInfo.getTypeName();
            if (type.equalsIgnoreCase("WIFI")) {
                mNetWorkType = NETWORK_TYPE_WIFI;
            } else if (type.equalsIgnoreCase("MOBILE")) {
                return isFastMobileNetwork(context) ? NETWORK_TYPE_4G : NETWORK_TYPE_2G;
            }
        } else {
            mNetWorkType = NETWORK_TYPE_NONE;//没有网络
        }
        return mNetWorkType;
    }

    /**
     * 判断网络类型
     */
    private static boolean isFastMobileNetwork(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        if (telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_LTE) {
            return true;
        }
        return false;
    }

    public static void getMobileNetworkSignal(Context mContext, PhoneStateListener listener) {
        TelephonyManager telephonyManager = (TelephonyManager)
                mContext.getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(listener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS
                | PhoneStateListener.LISTEN_CELL_INFO | PhoneStateListener.LISTEN_CELL_LOCATION);
        int dataState = telephonyManager.getDataState();
        LogUtils.i("dataState", "dataState = " + dataState);
    }

    public static void noneNetworkSignal(Context mContext, PhoneStateListener listener) {
        TelephonyManager telephonyManager = (TelephonyManager)
                mContext.getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE);
    }

    public static void getSignalStrength(Context mContext) {
        TelephonyManager telephonyManager = (TelephonyManager)
                mContext.getSystemService(Context.TELEPHONY_SERVICE);
        SignalStrength signalStrength = telephonyManager.getSignalStrength();
        for (CellSignalStrength cellSignalStrength : signalStrength.getCellSignalStrengths()) {
            if (cellSignalStrength.toString().contains("CellSignalStrengthLte")){
                //4G
                int dbm = cellSignalStrength.getDbm();
                LogUtils.i("dataState", "dbm = " + dbm);
            }
        }

    }

    public static int[] getSubId(Context context) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            List<SubscriptionInfo> list = SubscriptionManager.from(context).getActiveSubscriptionInfoList();
            if (ListUtils.isNoEmpty(list)) {
                int[] subList = new int[list.size()];
                for (int i = 0; i < list.size(); i++) {
                    SubscriptionInfo info = list.get(i);
                    subList[i] = info.getSubscriptionId();
                    LogUtils.i("dataState", "getSubscriptionId = " + info.getSubscriptionId());
                }
                return subList;
            }
        }
        return null;
    }

    public static void setListeningSimCard(int subId, PhoneStateListener phoneStateListener) {
        try {
            Field field = PhoneStateListener.class.getDeclaredField("mSubId");
            field.setAccessible(true);
            field.set(phoneStateListener, new Integer(subId));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

2、代码调用

private fun initData(){
        mHandler = object : Handler(Looper.getMainLooper()) {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                when (msg.what) {
                    0 -> {
                        phoneStateListener1 =
                            getMobileNetworkSignal(requireContext(), subId!![1], 1)
                        mHandler?.sendEmptyMessageDelayed(1, 1000)
                    }

                    1 -> {
                        noneNetwork(requireContext(), phoneStateListener)
                        noneNetwork(requireContext(), phoneStateListener1)
                        phoneStateListener = null
                        phoneStateListener1 = null
                    }

                    2 -> {
                        noneNetwork(requireContext(), phoneStateListener)
                        phoneStateListener = null
                        mHandler?.sendEmptyMessageDelayed(0, 100)
                    }
                }
            }
        }
} 

private fun getData() {
subId = PhoneUtils.getSubId(requireContext())
if (subId != null) {
    viewModel.resultInfo.value = ("${subId!!.size}张卡")
    if (subId!!.size > 1) {
        phoneStateListener = getMobileNetworkSignal(requireContext(), subId!![0], 0)
        mHandler?.sendEmptyMessageDelayed(2, 1000)
    } else {
        phoneStateListener = getMobileNetworkSignal(requireContext(), -1, 0)
          mHandler?.sendEmptyMessageDelayed(1, 1000)
     }
 } else {
     viewModel.resultInfo.value = ("无卡")
}
}

  private fun getMobileNetworkSignal(
        context: Context,
        subId: Int,
        position: Int
    ): PhoneStateListener {
        LogUtils.i(TAG, "subId = $subId")
        val phoneStateListener = object : PhoneStateListener() {
            override fun onSignalStrengthsChanged(signalStrength: SignalStrength) {
                super.onSignalStrengthsChanged(signalStrength)
                if (signalStrength != null) {
                    val level = signalStrength.level
                    LogUtils.i(TAG, "level = $level")
                    LogUtils.i(
                        TAG,
                        "signalStrength.isGsm = ${signalStrength.isGsm}"
                    )
                    val asu = signalStrength.gsmSignalStrength

                    LogUtils.i(
                        TAG, "asu = $asu"
                    )
                    if (asu != 99) {
                        val lastSignal = -113 + 2 * asu
                        LogUtils.i(
                            TAG,
                            "lastSignal = $lastSignal"
                        )
                        if (position == 0) {
                            viewModel.resultInfo.value =
                                ("卡1 信号:${level}  信号强度:${lastSignal}")
                        } else {
                            viewModel.resultInfo.value =
                                ("卡2 信号:${level}  信号强度:${lastSignal}")
                        }
                    } else {
                        for (cellSignalStrength in signalStrength.cellSignalStrengths) {
                            if (cellSignalStrength.toString().contains("CellSignalStrengthLte")) {
                                //4G
                                val dbm = cellSignalStrength.dbm
                                LogUtils.i(TAG, "dbm = $dbm")
                                if (position == 0) {
                                    viewModel.resultInfo.value =
                                        ("卡1 信号:${level}  信号强度:${dbm}")
                                } else {
                                    viewModel.resultInfo.value =
                                        ("卡2 信号:${level}  信号强度:${dbm}")
                                }
                            }
                        }
                    }
                }
            }
        }
        if (subId >= 0) {
            PhoneUtils.setListeningSimCard(subId, phoneStateListener)
        }
        PhoneUtils.getMobileNetworkSignal(context, phoneStateListener)
        return phoneStateListener
    }

    private fun noneNetwork(context: Context, phoneStateListener: PhoneStateListener?) {
        if (phoneStateListener != null) {
            PhoneUtils.noneNetworkSignal(context, phoneStateListener)
        }
    }

文章来源:https://blog.csdn.net/feibafeibafeiba/article/details/135478688
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。