问题
So I am calling few different web services in my app but I want to check if the device is able to connect to internet before service is called.
First I created a static Flag.
public static bool IsOfflineMode = false;
And before each service is called, I add the following:
if(IsOfflineMode) {
return;
}
This is how I am checking if the device is online or not.
public bool isConnected()
{
ConnectivityManager connectManager = (ConnectivityManager)GetSystemService (Context.ConnectivityService);
NetworkInfo netInfo = connectManager.ActiveNetworkInfo;
if (netInfo != null && netInfo.IsConnectedOrConnecting) {
NetworkInfo wifi = connectManager.GetNetworkInfo (ConnectivityType.Wifi);
NetworkInfo mobile = connectManager.GetNetworkInfo (ConnectivityType.Mobile);
if ((mobile != null && mobile.IsConnectedOrConnecting) || (wifi != null && wifi.IsConnectedOrConnecting)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
And then assign the value of isConnected()
to IsOfflineMode
.
IsOfflineMode = !isConnected ();
But I don't want to call isConnected()
every time.
How can I put a trigger so that when the device goes offline/online, it changes the value of IsOfflineMode
?
Thank you for your time.
回答1:
Create a BroadcastReceiver responding to the action <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
Hope it helps!
来源:https://stackoverflow.com/questions/28751528/android-network-reachability-offline-mode