0

I'm trying to use a BroadcastReceiver to detect if wifi is connected and simply display a toast when the status changes (wifi disonnect/reconnect/turn off) but it doesn't seem to be working. Any ideas?

ConnectionChangeReceiver class:

public class ConnectionChangeReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive( Context context, Intent intent )
    {
         ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 

         final boolean isWifiConn = networkInfo.isConnected();

         Log.d("debug", "Wifi connected: " + isWifiConn);

         Toast toast = Toast.makeText(context, "Wifi connected: " + isWifiConn, Toast.LENGTH_LONG);
         toast.show();     
    }
}

Manifest:

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />


    <receiver android:name="ConnectionChangeReceiver" android:label="NetworkConnection">
        <intent-filter>
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
            <action android:name="android.net.wifi.STATE_CHANGE"/>
        </intent-filter>
    </receiver>

I go in the app, and disconnect wifi, reconnect, no toast. I disable wifi, no toast. re-enable it, no toast. I suspect that there's something wrong with the broadcast receiver.

Thanks in advance.

Jonny07
  • 625
  • 3
  • 14

1 Answers1

0

I got it working.

My problem was in the Manifest. I was putting my receiver block outside the application tag. Once I moved it inside, it worked perfectly.

Jonny07
  • 625
  • 3
  • 14
  • I guess this'll fire multiple times when wifi is changed even once ? – Shivam Verma Jun 23 '14 at 16:02
  • Yes you're correct. When switching from WIFI off -> on I notice it fires twice. Once with isAvaialble() true && isConnected() false, and the second time with isAvailable() true && isConnected() true. It shouldn't be too stressful on the app though, and I haven't found another way around it. I believe this is the proper implementation. – Jonny07 Jun 23 '14 at 18:31