Know when network connectivity returns
I have an application that tries to be a good samaritan, basically, when any services start that needs to interact with the network. I am checking to see if the device has connectivity:
hasConnectivity Method
private boolean hasConnectivity() {
NetworkInfo info = mConnectivity.getActiveNetworkInfo();
boolean connected = false;
int netType = -1;
开发者_如何学Python int netSubtype = -1;
if (info == null) {
Log.w(sTag, "network info is null");
notifyUser(MyIntent.ACTION_VIEW_ALL, "There is no network connectivity.", false);
} else if (!mConnectivity.getBackgroundDataSetting()) {
Log.w(sTag, "background data setting is not enabled");
notifyUser(MyIntent.ACTION_VIEW_ALL, "background data setting is disabled", false);
} else {
netType = info.getType();
netSubtype = info.getSubtype();
if (netType == ConnectivityManager.TYPE_WIFI) {
connected = info.isConnected();
} else if (netType == ConnectivityManager.TYPE_MOBILE
&& netSubtype == TelephonyManager.NETWORK_TYPE_UMTS
&& !mTelephonyManager.isNetworkRoaming()
) {
connected = info.isConnected();
} else if (info.isRoaming()) {
notifyUser(MyIntent.ACTION_VIEW_ALL, "Currently Roaming skipping check.", false);
} else if (info.isAvailable()) {
connected = info.isConnected();
} else {
notifyUser(MyIntent.ACTION_VIEW_ALL, "..There is no network connectivity.", false);
}
}
return connected;
}
When this method returns false I know that I don't have a connection because the user is on the phone or 3g and wifi is not available
What is the best way to know when Connectivity is available without pulling the network stats with a timer periodically?
Is there an Intent action that I can observe with a broadcast receiver that will announce a change with connectivity?
Thanks for any help, I will keep searching the docs for some clue on what to do next.
This is what I have for checking Internet-access (actually, more like if the Wifi is enabled and connected to a network).
public class ConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION))
{
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
MainMap.setWifiState(wm.getWifiState());
Log.e("Debug", "Setting wifistate: " + wm.getWifiState());
} else if(action.equals(ConnectivityManager.CONNECTIVITY_ACTION))
{
NetworkInfo ni = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
MainMap.setConnected(ni.isConnected());
Log.e("Debug", "Setting isConnected: " + ni.isConnected());
if(ni.isConnected()) Toast.makeText(context, "Connected!", Toast.LENGTH_LONG).show();
}
}
}
It shouldn't be too hard to check if the user is on 3G or on Wifi.
精彩评论