Search code examples
androidbroadcastreceiverandroid-broadcastwifimanager

Why the WiFi broadCastReceiver dose not update the info received?


I seriously do not know what i am missing in the below code. Wha t I am trying to do is, to have some network and WiFi info displayed according to the current connectivity and to the WiFi current state. For an example, if the App is running and the user decided to turn the WiFi OFF, then, some text should be displayed automatically to show the current BSSID=00.00.00.00, speed= -1Mbps RSSI=0 and etc. And if the user decided to turn the WiFi ON, then, the same previously mentione info should displays its correspnding values.

To achieve this, I have created a broadCastReceiver for the WiFi as mentioned below in the code and I register this broadCastReceiver in onStart(), and unregister it in onStop().

What happens is,

Case_1:

if initially the WiFi is turned ON and I run the App, then every thing is fine and the App displays something as in the pic_0 below. But, at this state if i pressed the disconnect toggle button and pressed on it again to reconnect, then the App displays something like as in pic_1 below and does not display the info.

Case_2:

if initially the WiFi is turned OFF and I run the App, then I get something as in pic_2, and this is normal because there is not connection yet. But, in this case after pressing the connect toggle button, i get something as in pic_3, and dispite there is a connection, however, no info are displayed.

Above that, when I run the App, and try to connect to a network manually and go back to the App, it crashes and logcat says unable to unregister an unregistered receiver!!

Kinly please let me know what I am missing and what I did wrong.

Code

public class WiFi_Socket_04 extends Activity {

TextView tv_conn_status;
TextView tv_wifi_state;
TextView tv_conn_bssid;
TextView tv_conn_speed;
TextView tv_conn_strengt;
TextView tv_conn_ip;

EditText et_ip;
ToggleButton tog_connect;
EditText et_msg;
Button btn_send;

private boolean isWiFiReceiverRegistered = false;
private boolean isNetworkReceiverRegistered = false;

private final String network_service = Context.CONNECTIVITY_SERVICE;
private final String wifi_service = Context.WIFI_SERVICE;
private ConnectivityManager mConnMgr; 
private NetworkInfo networkInfo;
private WifiManager mWiFi_Mgr;
private WifiInfo mWiFi_Info;
private final String TAG = "wifi_socket_01";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.w(TAG, "@onCreate(");

    mWiFi_Mgr = (WifiManager) getSystemService(wifi_service);
    SetUpAllViews(R.layout.activity_main);
}

private void setViewState(int view, boolean state) {
    // TODO Auto-generated method stub
    switch(view) {
    case R.id.togbtn_connect: tog_connect.setEnabled(state);
    case R.id.et_ip: et_ip.setEnabled(state);
    case R.id.btn_send: btn_send.setEnabled(state);
    case R.id.et_msg: et_msg.setEnabled(state);
    }
}

private BroadcastReceiver mNetworkReceiver = new BroadcastReceiver() {

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

        mConnMgr = (ConnectivityManager)getSystemService(network_service);
        if (mConnMgr != null) {
            networkInfo = mConnMgr.getActiveNetworkInfo();
            if (networkInfo != null) {
                switch(networkInfo.getType()) {
                case ConnectivityManager.TYPE_WIFI: 
                    if (networkInfo.isConnected()) {
                        setText(R.id.tv_conn_status, ""+networkInfo);

                        setViewState(R.id.et_ip, true);
                        setViewState(R.id.btn_send, false);
                        setViewState(R.id.et_msg, false);

                    }else if (networkInfo.isConnectedOrConnecting()) {
                        setText(R.id.tv_conn_status, "Status: CONNECTED Or CONNECTING");
                    }else if (networkInfo.isFailover()){
                        setText(R.id.tv_conn_status, "Status: FailOver");
                    }else if (networkInfo.isRoaming()) {
                        setText(R.id.tv_conn_status, "Status: Roaming");
                    }else if (networkInfo.isAvailable()) {
                        setText(R.id.tv_conn_status, "Status: Available");
                    }
                    break;
                }
            }else {
                setText(R.id.tv_conn_status, "Status: No Default NetWork Connected");
            }
        }else {
            Log.e(TAG, "@mNetworkReceiverm(): ConnMgr is null");
        }
    }
};

private BroadcastReceiver mWiFiReceiver = new BroadcastReceiver() {

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

        /*if (mNetworkReceiverState == false) {
            if ( registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)) != null ) {
                mNetworkReceiverState = true;
                Log.i(TAG, "@onStart(): mNetworkReceiver registered, the sticky intent found");
            }else {
                Log.e(TAG, "@onStart(): mNetworkReceiver can not be registered, the sticky intent can not be found");
                }
        }*/

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

        switch(wifiExtras) {
        case WifiManager.WIFI_STATE_ENABLING: setText(R.id.tv_wifi_state, "Enabling..."); break;
        case WifiManager.WIFI_STATE_ENABLED:

            mConnMgr = (ConnectivityManager)getSystemService(network_service);
            if (mConnMgr != null) {
                networkInfo = mConnMgr.getActiveNetworkInfo();

                if (networkInfo != null) {

                    switch(networkInfo.getType()) {
                    case ConnectivityManager.TYPE_WIFI: 
                        if (networkInfo.isConnected()) {
                            setText(R.id.tv_conn_status, ""+networkInfo);
                            setViewState(R.id.et_ip, true);
                            setViewState(R.id.btn_send, false);
                            setViewState(R.id.et_msg, false);
                        }
                    }
                }
            if (mWiFi_Mgr != null)
                mWiFi_Info = mWiFi_Mgr.getConnectionInfo();

            setText(R.id.tv_wifi_state, "WIFi_State: Enabled");
            if (mWiFi_Info != null) {
                if (mWiFi_Info.getBSSID() != null) {
                    setText(R.id.tv_conn_bssid, "BSSID: "+mWiFi_Info.getBSSID());
                    }else {
                        setText(R.id.tv_conn_bssid, "BSSID: "+mWiFi_Info.getBSSID());
                        }
                setText(R.id.tv_conn_speed, "Speed: "+mWiFi_Info.getLinkSpeed()+WifiInfo.LINK_SPEED_UNITS);
                setText(R.id.tv_conn_strength, "RSSI: "+WifiManager.calculateSignalLevel(mWiFi_Info.getRssi(), 5));
                setText(R.id.tv_conn_ip, getIPv4(mWiFi_Info.getIpAddress()));
            }
            }
            break;

        case WifiManager.WIFI_STATE_DISABLING: setText(R.id.tv_wifi_state, "WIFi_State: Disabling..."); break;
        case WifiManager.WIFI_STATE_DISABLED:
            mConnMgr = (ConnectivityManager) getSystemService(network_service);
            if (mConnMgr != null) {
                networkInfo = mConnMgr.getActiveNetworkInfo();

                if (networkInfo != null) {
                    switch(networkInfo.getType()) {
                    case ConnectivityManager.TYPE_WIFI:
                        if ( (!networkInfo.isAvailable()) || (!networkInfo.isConnected()) ) {
                            setText(R.id.tv_conn_status, ""+networkInfo);
                            setViewState(R.id.et_ip, false);
                            setViewState(R.id.btn_send, false);
                            setViewState(R.id.et_msg, false);
                        }
                    }
                }
                if (mWiFi_Mgr != null)
                    mWiFi_Info = mWiFi_Mgr.getConnectionInfo();

                if (mWiFi_Info != null) {
                    if (mWiFi_Info.getBSSID() != null) {
                        setText(R.id.tv_conn_bssid, "BSSID: "+mWiFi_Info.getBSSID());
                        }else {
                            setText(R.id.tv_conn_bssid, "BSSID: "+mWiFi_Info.getBSSID());
                            }
                    setText(R.id.tv_conn_speed, "Speed: "+mWiFi_Info.getLinkSpeed()+WifiInfo.LINK_SPEED_UNITS);
                    setText(R.id.tv_conn_strength, "RSSI: "+WifiManager.calculateSignalLevel(mWiFi_Info.getRssi(), 5));
                    setText(R.id.tv_conn_ip, getIPv4(mWiFi_Info.getIpAddress()));
                }
            }
            setText(R.id.tv_wifi_state, "WIFi_State: Disabled");    
            break;

        case WifiManager.WIFI_STATE_UNKNOWN: setText(R.id.tv_wifi_state, "WIFi_State: Unkown_WiFi_State"); break;
        }
    }
};

@Override
protected void onStart() {
    // TODO Auto-generated method stub
    Log.w(TAG, "@onStart()");
    super.onStart();

    if (isWiFiReceiverRegistered == false) {
        if ( registerReceiver(mWiFiReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION)) != null ) {
            isWiFiReceiverRegistered = true;
            Log.i(TAG, "@onStart(): mWiFiReceiver registered, the sticky intent found");
        }else {
            Log.e(TAG, "@onStart(): mWiFiReceiver can not be registered, the sticky intent can not be found");
            }
    }

    if (mWiFi_Mgr != null) {
        if ( (mWiFi_Mgr.isWifiEnabled() == true) && (mWiFi_Mgr.getWifiState() == WifiManager.WIFI_STATE_ENABLED) ) {
            tog_connect.setChecked(true);
        }else {
            tog_connect.setChecked(false);
        }
    }

    tog_connect.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // TODO Auto-generated method stub
            if (isChecked) {
                if (mWiFi_Mgr != null) {
                    if ( (mWiFi_Mgr.isWifiEnabled() == false) && (mWiFi_Mgr.getWifiState() == WifiManager.WIFI_STATE_DISABLED) )
                        mWiFi_Mgr.setWifiEnabled(true);
                    }else {
                        Toast.makeText(getApplicationContext(), "WiFi is already ON", Toast.LENGTH_SHORT).show();
                    }
            }else {
                if (mWiFi_Mgr != null) {
                    if ( (mWiFi_Mgr.isWifiEnabled() == true) && (mWiFi_Mgr.getWifiState() == WifiManager.WIFI_STATE_ENABLED) ) { 
                        mWiFi_Mgr.setWifiEnabled(false);
                    }else {
                        Toast.makeText(getApplicationContext(), "WiFi is already OFF", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    });
}

private void SetUpAllViews(int layout) {
    // TODO Auto-generated method stub
    setContentView(layout);

    tv_conn_status = (TextView) findViewById(R.id.tv_conn_status);
    tv_wifi_state = (TextView) findViewById(R.id.tv_wifi_state);
    tv_conn_bssid = (TextView) findViewById(R.id.tv_conn_bssid);
    tv_conn_speed = (TextView) findViewById(R.id.tv_conn_speed);
    tv_conn_strengt = (TextView) findViewById(R.id.tv_conn_strength);
    tv_conn_ip = (TextView) findViewById(R.id.tv_conn_ip);
    et_ip = (EditText) findViewById(R.id.et_ip);
    tog_connect = (ToggleButton) findViewById(R.id.togbtn_connect);
    et_msg = (EditText) findViewById(R.id.et_msg);
    btn_send = (Button) findViewById(R.id.btn_send);
}

private void setText(int view, String text) {
    // TODO Auto-generated method stub
    switch(view) {
    case R.id.tv_conn_status: tv_conn_status.setText(text); break;
    case R.id.tv_wifi_state: tv_wifi_state.setText(text); break;
    case R.id.tv_conn_bssid: tv_conn_bssid.setText(text); break;
    case R.id.tv_conn_speed: tv_conn_speed.setText(text); break;
    case R.id.tv_conn_strength: tv_conn_strengt.setText(text); break;
    case R.id.tv_conn_ip: tv_conn_ip.setText(text); break;
    }
}

private String getIPv4(int ip) {
    // TODO Auto-generated method stub
    String result = String.format("%d.%d.%d.%d", (ip & 0xff), (ip >> 8 & 0xff), (ip >> 16 & 0xff),
            (ip >> 24 & 0xff));

    return result;
}


@Override
protected void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
    Log.w(TAG, "@onStop()");

    /*if (mNetworkReceiverState) {
        Log.d(TAG, "@onStop(): mNetworkReceiver unregistered");
        unregisterReceiver(mNetworkReceiver);
    }*/

    if (isWiFiReceiverRegistered) {
        Log.d(TAG, "@onStop(): mWiFiReceiver unregistered");
        unregisterReceiver(mWiFiReceiver);
    }
}

}

Pic_0 enter image description here

Pic_1: enter image description here

Pic_2: enter image description here

Pic_3: enter image description here


Solution

  • I suggest you read the documentation about BroadcastReceiver and WifiManager to properly understand how they work. I'd do the following:

    1.- Create an IntentFilter and register all the necessary actions that you want to listen.(WifiManager.WIFI_STATE_CHANGED_ACTION, WifiManager.NETWORK_STATE_CHANGED_ACTION)

    2.- Create a single broadcast receiver and add all of your logic in the onreceive() method.

    The combination of WIFI_STATE_CHANGED, NETWORK_STATE_CHANGED and all of the parcelables they receive should be more than enough to achieve what you are trying to do.