0

I am adding a wifi check to my app that prevents users from doing anything without a valid connection.

After researching some stackoverflow questions to this, I added this to my Main activity:

public AppWifiManager appWifiManager;

this.appWifiManager = new AppWifiManager();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        registerReceiver(this.appWifiManager, intentFilter);

        if(this.appWifiManager.connected){
            System.out.println("Connected to wifi!");
        }
        else{
            System.out.println("Not connected to wifi!");
        }

Next, appWifiManager is a class that extends BroadcastReceiver:

package flarehubpe.xflare.flarehub;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.Context;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;

public class AppWifiManager extends BroadcastReceiver{

    public boolean connected = false;

    @Override
    public void onReceive(Context context, Intent intent) {

        final String action = intent.getAction();

        System.out.println("CALLED");

        if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            this.connected = info.isConnected();
        }
    }

}

Lastly, in my android manifest I registered:

<receiver android:name="flarehubpe.xflare.flarehub.AppWifiManager">
            <intent-filter>
                <action android:name="android.net.wifi.STATE_CHANGE"/>
                <action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
            </intent-filter>
        </receiver>
<uses-permission android:name="android.permission.NETWORK_STATE_CHANGED_ACTION"/>
    <uses-permission android:name="android.permission.EXTRA_NETWORK_INFO"/>

I added some simple debug script and the code is not working. My override onReceive method never gets called. Why is android not calling my method? As a result I cannot get the true connectivity state of the app.

linux932
  • 963
  • 1
  • 8
  • 16
  • 1
    If all you need to do is check that you're WiFi connected, you don't need to use the BroadcastReceiver. I've found this simple check works well in most situations: http://stackoverflow.com/a/9028842/4409409 – Daniel Nugent May 03 '17 at 03:53
  • This might help: http://stackoverflow.com/questions/7050101/wifi-scan-results-broadcast-receiver-not-working Good luck! – Alex May 03 '17 at 04:06
  • @DanielNugent That worked perfectly, Thanks! – linux932 May 03 '17 at 04:12

0 Answers0