SignalStrength - getSignalStrength() - getLevel()
Asked Answered
B

1

3

I can easily get the sigalStrength in Android via callback

 onSignalStrengthsChanged(SignalStrength signalStrength)

and retrieve the signalStrength trough the passed object

int signal_strength = signalStrength.getGsmSignalStrength();

and according to the documentation the value varies between 0 and 39.99

Now I want to display this in my app in an indicator that updates as the signalStrenght varies - exactly what you can see in the statusbar on your phone.

So my question - how can I use the variable for this? If its linear its easy to just use intervalls from 1 - 10, 11 - 20 etc. But I guess its not that easy?

I know I can standardize this value just through a call to ..

 int level = signalStrength.getLevel()

That is by calling getLevel then I gets a value between 0 - 4, just as RSSI does for WIFI. But the problem is that it requires api 23 and that means I can only reach approx 40% of the android market.

So - If I do not want to use getLevel, how could I use getGsmSignalStrength() accordingly?

  @Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
    super.onSignalStrengthsChanged(signalStrength);

    int signal_strength = signalStrength.getGsmSignalStrength();

    //int level = signalStrength.getLevel(); //api 23

    Toast.makeText(context, "signalStrength: " + signal_strength, Toast.LENGTH_SHORT).show();
}
Bulldog answered 9/2, 2018 at 17:28 Comment(0)
B
2

Try following code snippet in your onSignalStrengthsChanged. I achieved it using reflection. It works for all type of network classes. Hope it helps.

@Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
    super.onSignalStrengthsChanged(signalStrength);

    int level = 0;
    try {
        final Method m = SignalStrength.class.getDeclaredMethod("getLevel", (Class[]) null);
        m.setAccessible(true);
        level = (Integer) m.invoke(signalStrength, (Object[]) null);
    } catch (Exception e) {
        e.printStackTrace();
    }          
}
Betide answered 6/3, 2018 at 14:29 Comment(2)
@Bulldog I am glad it helped you!Betide
how about in Kotlin?Lw

© 2022 - 2024 — McMap. All rights reserved.