Android 获取4G信号强度的方法

仅备份

package com.ztl.monitor4g;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.IBinder;
import android.os.Message;
import android.telephony.CellInfo;
import android.telephony.CellInfoLte;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;


import androidx.annotation.RequiresApi;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import ZtlApi.ZtlManager;

public class MainService extends Service {
    private static final String TAG = "MainService";
    public static String ver = "20201121";

    public static MainService Instatnce = null;
    TelephonyManager mTelephonyManager;
    MyPhoneStateListener myListener;

    public MainService() {
        Log.e("MainService()","MainService() 被调用");
        Instatnce = this;
    }

    @Override
    public void onCreate(){
        Log.e(TAG, "onCreate is call. ver:" + ver);
        ZtlManager.GetInstance().setContext(this);
        mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        if( Build.VERSION.SDK_INT <25 )
        {
            myListener = new MyPhoneStateListener();//5.1只能用这个
            mTelephonyManager.listen(null, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
            mTelephonyManager.listen(myListener, PhoneStateListener.LISTEN_NONE);
            mTelephonyManager.listen(myListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
        }else{
            //7.1 这个才是对的 5.1返回空
            new Thread(new Runnable() {
                @Override
                public void run() {
                    TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                    while (true){
                        @SuppressLint("MissingPermission") List cellInfoList = tm.getAllCellInfo();
                        if(cellInfoList != null){
                            for (CellInfo cellInfo : cellInfoList)
                            {
                                if (cellInfo instanceof CellInfoLte)
                                {
                                    //cast to CellInfoLte and call all the CellInfoLte methods you need
                                    int dbm = ((CellInfoLte)cellInfo).getCellSignalStrength().getDbm();
                                    int asu = ((CellInfoLte)cellInfo).getCellSignalStrength().getAsuLevel();

                                    String provider = getProvider();
                                    String celluarType = getCellularType();
                                    String logTxt = String.format("%s %s dbm:%d asu:%d \n", provider, celluarType, dbm, asu);
                                    logFile(logTxt, true);
                                    Log.i("mb_signal info",provider + " " + celluarType+ " dbm:" + dbm +" asu:" + asu);

                                    break;
                                }
                            }
                        }

                        try {
                            Thread.sleep(1000 );
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    //输出调试文本
    public static void logFile(String txt, boolean genDate) {
        String final_txt = "";
        if (genDate) {
            SimpleDateFormat dateformat = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]");
            String dateStr = dateformat.format(System.currentTimeMillis());
            final_txt = dateStr;
        }

        try {
            FileOutputStream outSTr = new FileOutputStream(new File("/sdcard/Download/4glog.txt"), true);
            BufferedOutputStream Buff = new BufferedOutputStream(outSTr);
            Buff.write(final_txt.getBytes());
            Buff.write(txt.getBytes());
            Buff.flush();
            Buff.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String getProvider(){
        @SuppressLint("MissingPermission")
        String IMSI = mTelephonyManager.getSubscriberId();
        //Log.i("qweqwes", "运营商代码" + IMSI);
        String ProvidersName = "Unknown";
        if (IMSI != null) {
            if (IMSI.startsWith("46000") || IMSI.startsWith("46002") || IMSI.startsWith("46007") || IMSI.startsWith("46004")) {
                ProvidersName = "中国移动";
            } else if (IMSI.startsWith("46001") || IMSI.startsWith("46006")) {
                ProvidersName = "中国联通";
            } else if (IMSI.startsWith("46003") || IMSI.startsWith("46011")) {
                ProvidersName = "中国电信";
            } else
                ProvidersName = IMSI;
        } else {
        }

        return ProvidersName;
    }

    @SuppressLint("MissingPermission")
    String getCellularType(){
        String cellularType="";
        int nSubType = mTelephonyManager.getNetworkType();
        if (nSubType == TelephonyManager.NETWORK_TYPE_GPRS
                || nSubType == TelephonyManager.NETWORK_TYPE_EDGE
                || nSubType == TelephonyManager.NETWORK_TYPE_CDMA
                || nSubType == TelephonyManager.NETWORK_TYPE_GSM) {
            cellularType = "2G";
        } else if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
                || nSubType == TelephonyManager.NETWORK_TYPE_HSDPA
                || nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0) {
            cellularType= "3G";
        } else if (nSubType == TelephonyManager.NETWORK_TYPE_LTE) {
            cellularType= "4G";
        } else if (nSubType == TelephonyManager.NETWORK_TYPE_NR) {
            cellularType= "5G";
        }else  if(nSubType == TelephonyManager.NETWORK_TYPE_UNKNOWN){
            cellularType= "0G";
        }else
           cellularType = String.valueOf( nSubType );

        return cellularType;
    }

    //5.1用这个
    private class MyPhoneStateListener extends PhoneStateListener {

        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            super.onSignalStrengthsChanged(signalStrength);

            try {
                Method method = signalStrength.getClass().getMethod("getDbm");
                int dbm = (int) method.invoke(signalStrength);

                Method method1 = signalStrength.getClass().getMethod("getAsuLevel");
                int asu = (int) method1.invoke(signalStrength);

                String provider = getProvider();
                String celluarType = getCellularType();
                String logTxt = String.format("%s %s dbm:%d asu:%d \n", provider, celluarType, dbm, asu);
                logFile(logTxt, true);
                Log.e("mb_signal info",provider + " " + celluarType+ " dbm:" + dbm +" asu:" + asu);

                //通过这个方法能获取出和系统一样的信号格数
                //Method method2 = signalStrength.getClass().getMethod("getLteLevel");
                //int level = method2.invoke(signalStrength);
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
                Log.d("TAG", "onSignalStrengthsChanged: 獲取4G訊號強度值失敗");
            }
        }

        @Override
        public void onServiceStateChanged(ServiceState serviceState) {
            int state = serviceState.getState();
            if( state == ServiceState.STATE_EMERGENCY_ONLY){
                Log.e("手机网络状态","STATE_EMERGENCY_ONLY");
                logFile("手机网络状态:STATE_EMERGENCY_ONLY\n", true);
            }else if( state == ServiceState.STATE_OUT_OF_SERVICE){
                Log.e("手机网络状态","STATE_OUT_OF_SERVICE");
                logFile("手机网络状态:STATE_OUT_OF_SERVICE\n", true);
            }else if( state == ServiceState.STATE_IN_SERVICE){
                Log.e("手机网络状态", "STATE_IN_SERVICE" );
                logFile("手机网络状态:STATE_IN_SERVICE\n", true);
            }else if(state == ServiceState.STATE_POWER_OFF)
            {
                Log.e("手机网络状态", "STATE_POWER_OFF" );
                logFile("手机网络状态:STATE_POWER_OFF\n", true);
            }else{
                Log.e("手机网络状态", "" + state);
                logFile("手机网络状态:" + state+"\n", true);
            }
        }
    }

}

既非原创也非抄袭。本人只做搬运和融合。特此声明

引用地址:

https://www.itread01.com/content/1545403538.html

https://blog.csdn.net/zjy764219923/article/details/104944238

https://www.it610.com/article/1293138498462752768.htm

你可能感兴趣的:(Android 获取4G信号强度的方法)