Android network reachability (offline mode)?

99封情书 提交于 2019-12-11 10:38:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!