Android的网络可达性(离线模式)? [英] Android network reachability (offline mode)?
问题描述
于是我打电话我的应用程序几个不同的网络服务,但我想检查设备能够连接到互联网被称为服务之前。
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.
公共静态布尔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;
}
}
,然后分配的值isConnected()
到 IsOfflineMode
。
IsOfflineMode = isConnected();!
但我不想叫 isConnected()
每次
怎样才能把一个触发器,这样,当设备进入离线/在线,它改变了 IsOfflineMode
How can I put a trigger so that when the device goes offline/online, it changes the value of IsOfflineMode
?
感谢您的时间。
推荐答案
创建广播接收器的应对行动<作用机器人:名字=android.net.conn.CONNECTIVITY_CHANGE/>
希望它帮助!
这篇关于Android的网络可达性(离线模式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!