Android获取手机信号强度/信号格数

这里的信号强度和格数是指状态栏里的信号条数目

比如这样有4条,获得的值就是4

需要先通过TMS注册一个监听,代码如下

    private static int mLteLevel = -1;

    /**
     * 监听手机信号变化
     */
    private static void listenSignalStrengths() {
        final TelephonyManager telephonyManager = (TelephonyManager) Core.context().getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager == null) {
            return;
        }
        telephonyManager.listen(new PhoneStateListener() {
            @Override
            public void onSignalStrengthsChanged(SignalStrength signalStrength) {
                super.onSignalStrengthsChanged(signalStrength);
                try {
                    Method getLteLevelMethod = signalStrength.getClass().getMethod("getLteLevel");
                    mLteLevel = DataUtils.getInt(getLteLevelMethod.invoke(signalStrength));
                    Log.i("NetUtil", "onSignalStrengthsChanged:" + mLteLevel);
                } catch (Throwable e) {
                    Log.i("NetUtil", "onSignalStrengthsChanged:" + e);
                }
            }
        }, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    }

mLteLevel作为成员变量,当信号强度发生变化时,他会自己更新,再提供一个getter就可以了

    /**
     * 获取手机信号强度格数,一般为 0-4
     */
    public static int getLteLevel() {
        return mLteLevel;
    }

给listenSignalStrengths方法找住处比较麻烦,所以可以放在静态代码块里,整体就像这样,调用getLteLevel获取就可以了。

不过需要注意的是,第一次取的时候可能是默认值-1,介意的话就把listenSignalStrengths提前到Application也可以。

public class NetUtil {

    public static final String TAG = "NetUtil";

    static {
        listenSignalStrengths();
    }

    /**
     * 监听手机信号变化
     */
    private static void listenSignalStrengths() {
        final TelephonyManager telephonyManager = (TelephonyManager) Core.context().getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager == null) {
            return;
        }
        telephonyManager.listen(new PhoneStateListener() {
            @Override
            public void onSignalStrengthsChanged(SignalStrength signalStrength) {
                super.onSignalStrengthsChanged(signalStrength);
                try {
                    Method getLteLevelMethod = signalStrength.getClass().getMethod("getLteLevel");
                    mLteLevel = DataUtils.getInt(getLteLevelMethod.invoke(signalStrength));
                    NTLog.i(TAG, "onSignalStrengthsChanged:" + mLteLevel);
                } catch (Throwable e) {
                    NTLog.i(TAG, "onSignalStrengthsChanged:" + e);
                }
            }
        }, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    }

    /**
     * 获取手机信号强度格数,一般为 0-4
     */
    public static int getLteLevel() {
        return mLteLevel;
    }
}

 

你可能感兴趣的:(Android,android,android,studio)