Listening WIFI state

こ雲淡風輕ζ 提交于 2019-11-28 12:26:48
denza

The android system asks to switch to Data Traffic when WiFi is not connected but there is an issue.
If you turn off WiFi when screen is off, it will constantly change between WiFi and 3G network and if you have selected apps to send data in the background, it will use the data connection which is costlier if you don't have unlimited data plan.
Another issue is when you are in a area with not so strong WiFi signal, it will constantly change to Data Traffic and you will have issues with browsing or whatever.
Third issue is battery as from what I've heard it's better(battery wise) to use the WiFi connection than the data, with one Add-on don't turn off WiFi when the screen is off.(even, I do so)because turning it off and on WiFi is most costly(battery) that to be always On. so therefore leave it to the android system.

Chris

I came across that problem too, here's how I solved it.

In my activity onCreate(..) I did

this.registerReceiver(mWifiStateChangedReceiver,new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));

and additionally i created the member 'mWifiStateChangedReceiver' this way

private BroadcastReceiver mWifiStateChangedReceiver = new BroadcastReceiver()
{

    @Override
    public void onReceive(Context context, Intent intent)
    {
        // TODO Auto-generated method stub

        int extraWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);

        switch (extraWifiState)
        {
        case WifiManager.WIFI_STATE_DISABLED:
        case WifiManager.WIFI_STATE_DISABLING:
            enableUI(false);
            break;
        case WifiManager.WIFI_STATE_ENABLED:
            ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
            while(conMan.getActiveNetworkInfo() == null || conMan.getActiveNetworkInfo().getState() != NetworkInfo.State.CONNECTED)
            {
                try
                {
                    Thread.sleep(500);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
            update();
            enableUI(true);
            break;
        case WifiManager.WIFI_STATE_ENABLING:
            break;
        case WifiManager.WIFI_STATE_UNKNOWN:
            break;
        }

    }
};

As you can see, when I get WifiManager.WIFI_STATE_ENABLED I additionally test if the network is really connected, because a enabled WiFi doesn't mean it's connected. At least this was my guess, that's why I'm waiting till the network is really connected.

If you want to listen to signal strength you can also listen at:

WifiManager.RSSI_CHANGED_ACTION

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!