In my application, I need to restart the service if the network change changes. Currently, it works only in one direction (wifi to mobile data), but it does not work in another way (mobile data for Wi-Fi). Why is this? Is it because I am not getting android.net.wifi.WIFI_STATE_CHANGED in my broadcast receiver, or maybe for the wrong resolution?
Thanks for any help.
code: Record manifest for the recipient:
<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 listed by me:
- android.permission.ACCESS_WIFI_STATE
- android.permission.ACCESS_NETWORK_STATE
- android.permission.INTERNET
Thanks again!
source share