Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

telephony - Get Signal Strength in Android

I want to get the Signal Strength of the Device at the point I hit the API call. I have searched on all the related threads and I am not successful yet.

So I would like to get the signal strength like

SignalStrength ss = null  ; // some initialization

int n = ss.getGsmSignalStrength();

But while using this, it is obvious that I will get null pointer exception since I have initialised SignalStrength as null. But I don't know how to initialise this.

Also that I don't want to use PhoneStateListener because it is triggered only if the signal changes.

I am getting the Signal Strength using the below code

TelephonyManager telephonyManager = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
CellInfoGsm cellinfogsm = (CellInfoGsm)telephonyManager.getAllCellInfo().get(0);
CellSignalStrengthGsm cellSignalStrengthGsm = cellinfogsm.getCellSignalStrength();
cellSignalStrengthGsm.getDbm();

But I don't want to use CellSignalStrength because it is only added in API Level 17 and will not work under 17. I want the code to work on API Level 7+.

Or is there any other method, so that I could get the signal strength at the point of hitting the API call?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Define Variables:

TelephonyManager mTelephonyManager;
MyPhoneStateListener mPhoneStatelistener;   
int mSignalStrength = 0;

Then add this class to your code:

class MyPhoneStateListener extends PhoneStateListener {

     @Override
     public void onSignalStrengthsChanged(SignalStrength signalStrength) {
         super.onSignalStrengthsChanged(signalStrength);
         mSignalStrength = signalStrength.getGsmSignalStrength();
         mSignalStrength = (2 * mSignalStrength) - 113; // -> dBm           
     }
 }

and in your onCreate method use:

mPhoneStatelistener = new MyPhoneStateListener();
mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
mTelephonyManager.listen(mPhoneStatelistener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...