Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android.net.wifi.WIFI_STATE_CHANGED not being broadcast

In my app, I need a service restarted if a network change is connected. Currently it only works one way (wifi to mobile data) but it doesn't work the other way (mobile data to wifi.) Why is this? Is it because I'm not getting android.net.wifi.WIFI_STATE_CHANGED in my broadcast receiver or maybe a misplaced permission?

Thanks for any help.

Code: Manifest entry for receiver:

<receiver
    android:name="LiveForever"
    android:label="NetworkChangeReceiver" >
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
    </intent-filter>
</receiver>

The receiver itself:

public static final int TYPE_WIFI = 1;
public static final int TYPE_MOBILE = 2;
public static final int TYPE_NOT_CONNECTED = 0;
public static final String PREFS_NAME = "cakecloudpreferences";

@Override
public void onReceive(Context context, Intent intent) {
    SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
    if (getConnectivityStatus(context)!=0&&!settings.getBoolean("osmframerunning",false)) {
        context.stopService(new Intent(context, OSMFrame.class));
        settings.edit().putBoolean("osmframerunning",false).commit();
        Intent frameintent = new Intent(context,OSMFrame.class);
        frameintent.putExtra("username",settings.getString("usr",""));
        frameintent.putExtra("password",settings.getString("pswd",""));
        frameintent.putExtra("uid",settings.getString("uid",""));
        context.startService(frameintent);
        Log.i("CCLiveForever","LiveForever Triggered, OSMFrame restarted.");
    }
}

public int getConnectivityStatus(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (null != activeNetwork) {
        if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) return TYPE_WIFI;
        if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) return TYPE_MOBILE;
    } 
    return TYPE_NOT_CONNECTED;
}

Relevant permissions I have listed:

  • android.permission.ACCESS_WIFI_STATE
  • android.permission.ACCESS_NETWORK_STATE
  • android.permission.INTERNET

Again, thank you!

like image 375
Osmium USA Avatar asked Jul 29 '13 16:07

Osmium USA


1 Answers

android.net.wifi.WIFI_STATE_CHANGED is sent only when WiFi is enabled or disabled. You need to catch android.net.wifi.STATE_CHANGE too if you want to receive broadcast event when you are connected to or disconnected from a WiFi network.

like image 104
hunyadym Avatar answered Oct 20 '22 10:10

hunyadym