Retrieve GSM signal strength in Android

前端 未结 3 1590
后悔当初
后悔当初 2021-02-10 00:54

I\'m a newbie to Android.

How do I get the GSM signal Strength in terms of percentage (1 - 100%)?

3条回答
  •  梦谈多话
    2021-02-10 01:40

        public class MyActivity extends Activity {
        public static final int UNKNOW_CODE = 99;
        int MAX_SIGNAL_DBM_VALUE = 31;
    
        TelephonyManager tel;
    MyPhoneStateListener myPhoneStateListener;
    
        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = getLayoutInflater().inflate(R.layout.activity_about, null);
        setContentView(view);
    
        myPhoneStateListener = new MyPhoneStateListener();
        tel = (TelephonyManager) PpsApplication.getAppContext().getSystemService(Context.TELEPHONY_SERVICE);
        tel.listen(myPhoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    }
    
    private class MyPhoneStateListener extends PhoneStateListener {
        /* Get the Signal strength from the provider, each tiome there is an update */
        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            super.onSignalStrengthsChanged(signalStrength);
    
            if (null != signalStrength && signalStrength.getGsmSignalStrength() != UNKNOW_CODE) {
                int signalStrengthPercent = calculateSignalStrengthInPercent(signalStrength.getGsmSignalStrength());
                viewModel.setSignalStrengthString(IntegerHelper.getString(signalStrengthPercent));
            }
        }
    }
    
    private int calculateSignalStrengthInPercent(int signalStrength) {
        return (int) ((float) signalStrength / MAX_SIGNAL_DBM_VALUE * 100);
    }
    
    }
    

提交回复
热议问题