Know when network connectivity will return

I have an application that tries to be a good Samaritan, mainly when any services that should interact with the network are launched. I check if the device has the ability to connect:

HasConnectivity Method

private boolean hasConnectivity() {
    NetworkInfo info = mConnectivity.getActiveNetworkInfo();
    boolean connected = false;
    int netType = -1; 
    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 do not have a connection, because the user is on the phone or 3G and Wi-Fi is not available

What is the best way to find out about connection availability without periodically checking network statistics using a timer ?

Is there any intentional action that I can observe with a broadcast receiver that will announce a change with the connection?

, , , .

+3
1

, ( , , Wi-Fi ).

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();
    }
}

}

, 3G Wi-Fi.

+3

Source: https://habr.com/ru/post/1779774/


All Articles