獲取手機資料訊號強度dbm數值
阿新 • • 發佈:2018-12-21
#####工具類
/** * 獲取手機資料訊號強度值工具類 * dbm的值為負數 * 0為最強訊號值 * -85以內為滿格訊號 */ public class PhoneNetUtil { private static final int DBM_1 = -85; private static final int DBM_2 = -95; private static final int DBM_3 = -105; private static final int DBM_4 = -115; private static final int DBM_5 = -140; private static final String TAG = "PhoneNetUtil"; private static PhoneNetUtil phoneNetUtil; private Context context; private PhoneNetListener phoneNetListener; private PhoneNetLevelListener phoneNetLevelListener; private PhoneNetUtil(Context context) { this.context = context; getNetDBM(context); } public static PhoneNetUtil getInstance(Context context) { if (phoneNetUtil == null) { phoneNetUtil = new PhoneNetUtil(context); } return phoneNetUtil; } public void setPhoneNetListener(PhoneNetListener phoneNetListener) { this.phoneNetListener = phoneNetListener; } public void setPhoneNetLevelListener(PhoneNetLevelListener phoneNetLevelListener) { this.phoneNetLevelListener = phoneNetLevelListener; } /** * 得到當前手機4G訊號強度值dbm */ private void getNetDBM(Context context) { final TelephonyManager tm = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); PhoneStateListener phoneStateListener = new PhoneStateListener() { @Override public void onSignalStrengthsChanged(SignalStrength signalStrength) { super.onSignalStrengthsChanged(signalStrength); //通過反射獲取當前訊號值 try { Method method = signalStrength.getClass().getMethod("getDbm"); int dbm = (int) method.invoke(signalStrength); Log.d(TAG, "4G-dbm: " + dbm); if (phoneNetListener != null) { phoneNetListener.onNetDbm(dbm); } setNetLevel(dbm); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); Log.d(TAG, "onSignalStrengthsChanged: 獲取4G訊號強度值失敗"); } } }; //開始監聽 if (tm != null) { tm.listen(phoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); } else { Log.d(TAG, "get4GNetDBM: TelephonyManager為空,獲取手機狀態資訊失敗,無法開啟監聽"); } } /** * 1、當訊號大於等於 - 85d Bm時候,訊號顯示滿格 * 2、當訊號大於等於 - 95d Bm時候,而小於 - 85d Bm時,訊號顯示4格 * 3、當訊號大於等於 - 105d Bm時候,而小於 - 95d Bm時,訊號顯示3格,不好捕捉到。 * 4、當訊號大於等於 - 115d Bm時候,而小於 - 105d Bm時,訊號顯示2格,不好捕捉到。 * 5、當訊號大於等於 - 140d Bm時候,而小於 - 115d Bm時,訊號顯示1格,不好捕捉到。 * * @param dbm */ private void setNetLevel(int dbm) { if (phoneNetLevelListener != null) { if (dbm > DBM_1) { phoneNetLevelListener.onNetLevel(5); } else if (DBM_2 < dbm && dbm < DBM_1) { phoneNetLevelListener.onNetLevel(4); } else if (DBM_3 < dbm && dbm < DBM_2) { phoneNetLevelListener.onNetLevel(3); } else if (DBM_4 < dbm && dbm < DBM_3) { phoneNetLevelListener.onNetLevel(2); } else if (DBM_5 < dbm && dbm < DBM_4) { phoneNetLevelListener.onNetLevel(1); } else { phoneNetLevelListener.onNetLevel(0); } } } /** * 當前的訊號強度值 dbm */ interface PhoneNetListener { void onNetDbm(int dbm); } /** * 訊號強度顯示格子數 * 最強訊號 5 --> 0 最弱訊號 */ interface PhoneNetLevelListener { void onNetLevel(int level); } }