Sunday, February 17, 2013

WIFI Signal Strength in Android

This evening I did some significant cleanup on the Android code that will control the robot/rover. I also decided it would be nice to be able to tell if you were about to drive off past your WIFI range, so I looked at how it can be measured.

 I had added a WifiManager object earlier to lock the Wifi so that it would not be throttled back by the phone. It quite reasonably does this to save power, but you don't want that to happen if you are using the wireless link to drive around, so the application requests a lock at startup and releases it on shutdown.

 If you have a WifiManager, it's easy to ask it the current state of the link, and it will return a bunch of information including signal strength in dB. If you want it to report "bars", it has a function to compute how many bars you are getting on whatever scale you prefer. Since I want a simple color coded indicator on the client control panel, I just went for a 0-5 bar scale.

 Here's the relevant code for reading signal strength and requesting/releasing WIFI locks:

import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.net.wifi.WifiInfo;

//owned by the class

WifiManager wifiManager = null;
WifiLock lock = null;
Integer signalStrength = 0;

//Prevent Android from throttling the wifi back to save batteries
private void obtainWifiLock()
{
if (!lock.isHeld()) 
 lock.acquire(); 
}
 
private void releaseWifiLock()
{
if (lock != null) 
     if (lock.isHeld()) 
            lock.release(); 
}
 
 
private void updateWifiStats()
{
//currently just updates the WIFI signal level
Integer numLevels = 6;
  
WifiInfo currentInfo = null;
 
currentInfo = wifiManager.getConnectionInfo();
signalStrength = wifiManager.calculateSignalLevel(currentInfo.getRssi(), numLevels);
  
}

6 comments:

  1. Thanks a ton Jason!!. u just stopped my googling. still i have some doubt about numLevels fields. Could you please explain about this and can we pass any number into numLevels. :( . m not clear about this numLevels field.I need to knw like whether the wifi signal is strong..good..poor..

    if possible can you please help me out on how to access the cellular signal strength in lower version devices. appreciate ur help.

    ReplyDelete
  2. Hi:

    The numLevels integer is the maximum number of "bars" you want to be measuring. So if you sent that to five, you will get back a signal strength indicating from 0-5 "bars". It's just a convenient arbitrary measurement. I have not looked into how to get the cell strength back, sorry.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete