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:
Again, thank you!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With