Android 5G判斷

之前需要用到5G網絡信息,花了很長時間纔去研究怎麼判斷是否是5G信號,但無論是官方說明的CellInfoNr,CellIdentityNr,CellSignalStrengthNr,最後連一個網絡連接callback都用過了,在華爲mate30 5G版上拿到的都是LTE(13),真的是心態爆炸。

一次偶然的機會看到ServiceState類,發現它有一個getNrState的方法,查了一下,返回爲3的時候就是5G網絡,詳細代碼如下
 

   /**
     * Get the NR 5G state of the mobile data network.
     * @return the NR 5G state.
     * @hide
     */
    public @NRState int getNrState() {
        final NetworkRegistrationInfo regInfo = getNetworkRegistrationInfo(
                NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
        if (regInfo == null) return NetworkRegistrationInfo.NR_STATE_NONE;
        return regInfo.getNrState();
    }

是一個隱藏的方法,但還是迫不及待的用反射試了一下
 

private boolean is5GConnected(){
       TelephonyManager telephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
        if(Build.VERSION.SDK_INT >= 26){
            ServiceState serviceState = telephonyManager.getServiceState();
            try{
                Method getNrStateMethod = ServiceState.class.getMethod("getNrState");
                getNrStateMethod.setAccessible(true);
                int result = (int)getNrStateMethod.invoke(serviceState);
                MyLog.i("ALeeObj", "值爲:" + result);
                if(result == 3){
                    return true;
                }else{
                    return false;
                }
            }catch (Exception e){
                MyLog.i("ALeeObj", e.toString());
            }
        }
        return false;
    }

結果就是那麼憂傷,給我整個這個
 

java.lang.NoSuchMethodException: android.telephony.ServiceState.getNrState []

說實話,當時脾氣都有點上來了,直接破罐子破摔,我就看看ServiceState這都整一些什麼方法,直接就寫了
 

Method []methods = ServiceState.class.getDeclaredMethods();
                for(Method method: methods){
                    MyLog.i("ALeeObj", method.getName());
                }

沒錯,就是把所有的方法都打印出來,結果給我看到了這玩意

看到這個我真的很激動,不會是華爲自己弄得一個吧,趕緊把返回類型和傳參類型都打印一下,發現沒有傳參,返回類型就是一個int,最後試了一下,果然,成了,最終代碼如下:

private boolean is5GConnected(){
       TelephonyManager telephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
        if(Build.VERSION.SDK_INT >= 29){
            ServiceState serviceState = telephonyManager.getServiceState();
            try{
                Method hwOwnMethod = ServiceState.class.getMethod("getHwNetworkType");
                hwOwnMethod.setAccessible(true);
                int result = (int)hwOwnMethod.invoke(serviceState);
                MyLog.i("ALeeObj", "值爲:" + result);
                if(result == 20){
                    return true;
                }else{
                    return false;
                }
            }catch (Exception e){
                MyLog.i("ALeeObj", e.toString());
            }
        }
        return false;
    }

試了一下,值就是官方NetworkType的值,比如nr就是20,lte就是13等等。
說明一下,這個方法只是華爲mate30 5G的有效,其他有沒效果,我也不清楚,手上只有這一臺測試機,而且我懷疑,自己懷疑啊,是華爲手機特有的一個方法,所以什麼時候失效也不清楚,大家如果要用,最好做一下心理準備。。。
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章