How to handle network change between wifi and mobile data?

how to handle slow network connection in android
auto switch between wifi and mobile data
how to turn on mobile data on android programmatically
android data usage programmatically
how to check internet connection in android programmatically
check internet connection in background android
android check internet connection listener
android monitor network traffic programmatically

I am building a VoIP app.During a VoIP call when user switches between WiFi to mobile data i have a problem handling the scenario.

In my call screen activity I have registered for receiver which helps me get notified about the network change scenarios.

This is the code which I am using for detecting change in networks in the onRecieve Method. conn_name is private class level variable holding previous connection name.

ConnectivityManager connectivity_mgr = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
NetworkInfo net_info = connectivity_mgr.getActiveNetworkInfo();

if (net_info != null && net_info.isConnectedOrConnecting() && !conn_name.equalsIgnoreCase("")) {
    new_con = net_info.getExtraInfo();
    if (new_con != null && !new_con.equalsIgnoreCase(conn_name))
        network_changed = true;
    conn_name = (new_con == null) ? "" : new_con;
    connectionStatus ="connected";
} else {
    if (net_info != null && conn_name.equalsIgnoreCase("")) {
        conn_name = net_info.getExtraInfo();
        connectionStatus ="connected";
        network_changed = true;
    } else if(!new_con.equals(conn_name)) {
        conn_name = "";
        connectionStatus ="disconnected";
        network_changed = true;
    }
}

So using above method I able detect network changes. But one peculiar thing happens when I am connected with WiFi. When my app starts initially it is connected with mobile data.when user enters into his known WiFi area,he gets connected to his known WiFi. Since WiFi is always chosen as default route,android switches to WiFi and I receive the network notification that WiFi has been turned on.

So I update my apps IP address to WiFi IP address, so no issues here. But still mobile data is still connected at the same time but getActiveNetworkInfo() tells me that I'm connected with WiFi clearly even if I was early connected to mobile data.

So the problem is when user switches off the WiFi button,and mobile data is still connected but I still receive the notification for WiFi turn off. It indicates me that network is disconnected even when my phone is still connected to mobile data.

But after a second I receive a notification that mobile data is connected. But once I receive the network disconnected, I have closed my VoIP call. So when I receive a notification for WiFi switched off how can I make sure whether mobile data is still connected.

I tried getActiveNetworkInfo() but it happens to be null when I receive notification for WiFi turned off.

I have followed this links:

Android API call to determine user setting "Data Enabled" How to tell if 'Mobile Network Data' is enabled or disabled (even when connected by WiFi)?

Using the above link I am able detect that mobile data button has been enabled when user has connected with mobiledata.it gives me true. But the problem happens when this particular case happens.

Now when wifi is disabled I get notification but it shows that mobile data is disabled even when my mobile data is enabled. I am not able to handle this situation as I disconnect my calls when I receive my disconnected notification.

You can utilize APIs of ConnectivityManager: particularly in your use case you are interested in registerDefaultNetworkCallback():


    public class TestActivity extends AppCompatActivity {

        private ConnectivityManager manager;
        private final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                super.onAvailable(network);
                // this ternary operation is not quite true, because non-metered doesn't yet mean, that it's wifi
                // nevertheless, for simplicity let's assume that's true
                Log.i("vvv", "connected to " + (manager.isActiveNetworkMetered() ? "LTE" : "WIFI"));
            }

            @Override
            public void onLost(Network network) {
                super.onLost(network);
                Log.i("vvv", "losing active connection");
            }
        };

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            manager.registerDefaultNetworkCallback(networkCallback);
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            manager.unregisterNetworkCallback(networkCallback);
        }
    }

My device connects to LTE in about half second.

This means, that you cannot know beforehand, whether device will eventually connect to LTE or no at the time, when WIFI gets disconnected. Thus, you can adopt following approach: post an action on a handler to happen in a second and within this action cancel the call. If connection appears anytime soon - unschedule previously posted action. If you end up being in Runnable code, then connection wasn't established quickly, which means, that you should end the call.


    public class TestActivity extends AppCompatActivity {

        private ConnectivityManager manager;

        private final Handler handler = new Handler();
        private final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                super.onAvailable(network);
                Log.i("vvv", "connected to " + (manager.isActiveNetworkMetered() ? "LTE" : "WIFI"));

                // we've got a connection, remove callbacks (if we have posted any)
                handler.removeCallbacks(endCall);
            }

            @Override
            public void onLost(Network network) {
                super.onLost(network);
                Log.i("vvv", "losing active connection");

                // Schedule an event to take place in a second
                handler.postDelayed(endCall, 1000);
            }
        };

        private final Runnable endCall = new Runnable() {
            @Override
            public void run() {
                // if execution has reached here - feel free to cancel the call
                // because no connection was established in a second
            }
        };

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            manager.registerDefaultNetworkCallback(networkCallback);
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            manager.unregisterNetworkCallback(networkCallback);
            handler.removeCallbacks(endCall);
        }
    }

The downside of the approach is, that registerDefaultNetworkCallback() is available starting from API 24. There does not exist an alternative in ConnectivityManagerCompat either. Instead, you can use registerNetworkCallback() which is available from API 21.

How to handle network change between wifi and mobile data , You can utilize APIs of ConnectivityManager : particularly in your use case you are interested in registerDefaultNetworkCallback() : public class TestActivity� I am building a VoIP app.During a VoIP call when user switches between WiFi to mobile data i have a problem handling the scenario. In my call screen activity i have registered for receiver which helps me get notified about the network change scenarios.

You can use BroadcastReceiver and register NETWORK_STATE_CHANGED_ACTION & WIFI_STATE_CHANGED_ACTION.

private boolean isConnected;

final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null || intent.getAction() == null)
            return;
        switch (intent.getAction()){
            case WifiManager.NETWORK_STATE_CHANGED_ACTION :
            case WifiManager.WIFI_STATE_CHANGED_ACTION :
                if (!isConnected && isOnline(BaseActivity.this)) {
                    isConnected = true;
                    // do stuff when connected
                    Log.i("Network status: ","Connected");
                }else{
                    isConnected = isOnline(BaseActivity.this);
                    Log.i("Network status: ","Disconnected");
                }
                break;
        }
    }
};



@Override
protected void onCreate(Bundle savedInstanceState) {
    isConnected = isOnline(this);
    final IntentFilter filters = new IntentFilter();
    filters.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    filters.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    registerReceiver(broadcastReceiver, filters);
}


public static boolean isOnline(Context ctx) {
    ConnectivityManager cm = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm != null
            ? cm.getActiveNetworkInfo()
            : null;
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

Update Don't forget to unregisterReceiver BroadcastReceiver onDestroy

@Override
protected void onDestroy() {
    unregisterReceiver(broadcastReceiver);
    super.onDestroy();
} 

Auto Switch Between Wi-Fi & Mobile Data Networks, To allow your Galaxy S 5 to auto switch between Wi-Fi and mobile data, view this. to switch from a weak or unstable Wi-Fi network to the Verizon Wireless cellular network to preserve consistent data Related Topic: Manage Data Usage. I have maintained one background service which checks for network, but im not getting how to handle network switch WiFi to Mobile and Mobile to WiFi? I am not getting how to handle WiFi to mobile network switch because already WiFi is enabled and I am not in WiFi coverage area; in this situation I want to get switched to mobile network

My implementation with RxJava

class ConnectivityMonitor : ConnectivityManager.NetworkCallback() {
    var networkTimeout: Disposable? = null

    override fun onAvailable(network: Network?) {
        super.onAvailable(network)
        Timber.d("Network available")
        networkTimeout?.dispose()
    }

    override fun onLosing(network: Network?, maxMsToLive: Int) {
        super.onLosing(network, maxMsToLive)
        Timber.d("onLosing")
    }

    override fun onLost(network: Network?) {
        super.onLost(network)
        Timber.d("onLost")

        networkTimeout = Single.timer(5, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { _ -> Timber.d("Network lost") }
    }

    override fun onUnavailable() {
        super.onUnavailable()
        Timber.d("Network unavailable")
    }
}

Listener setup:

    private fun setupListeners() {
        // connection listener
        val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            connectivityManager.registerDefaultNetworkCallback(connectivityMonitor)
        } else {
            val builder = NetworkRequest.Builder()
            connectivityManager.registerNetworkCallback(builder.build(), connectivityMonitor)
        }
    }

The use of the timer / disposable allows for delays between switching connection types.

Manage network usage, Overview � Handle configuration changes Overview � Load and display paged data � Page from network and database Transmit network data using Volley for internet connectivity � Wi-Fi Network Request API for peer-to-peer connectivity. A Wi-Fi connection sends that individual piece of mobile data from one device to another through a complicated network of cell towers, IP connected stations and other types of network architecture. Companies and professionals apply all sorts of security and data handling applications to Wi-Fi systems that deliver mobile data in various ways.

How to Use WiFi and Data at the Same Time on Android, Just connect to both networks and use Speedify to combine them. The Only Way to Use WiFi and Cellular Data Simultaneously on Android Not alternatively, switching between them, but at the same time, simultaneously. But in case wifi on , mobile data on then priority must be to accomplish all work through wifi network but still after being connected to wifi the mobile data is used to accomplish the work. To work over wifi I have to switch off my mobile data then the wifi connection is used by mobile apps..

Fix internet connection problems on Android devices, If restarting doesn't work, switch between Wi-Fi and mobile data: Open your Settings app Settings and then "Wireless & networks" or "Connections". Depending� The Wi-Fi Alliance approves devices which are fully WiFi compatible with a “WiFi Certified” logo. Just like mobile data, there are also multiple variables to keep in mind with this technology. WiFi Coverage and Range. Much like mobile data, the strength and distance of a Wi-Fi signal diminish based on surroundings.

Limit how much mobile data Google Duo uses - Android, Keep in mind, Duo works over Wi-Fi and cellular data so you can make calls Note: When your device is connected to Wi-Fi, Duo still uses a small amount of mobile data. If you want to lower your data use or change your call quality, you can limit, If you can't connect to a Wi-Fi network, Duo automatically lowers your � How To Use Mobile Data & WiFi Simultaneously. We will be using two apps called “Speedify” & “Super Download” to combine WiFi Internet and Cellular Mobile Data. Both Apps came with FREE as well as Paid Versions. These Apps are very useful when you are suffering from low connectivity issues. Speedify is a new kind of VPN. It combines Wi

Comments
  • You can keep a pause of 1-2 seconds when the wifi is disconnected. And then after 1-2 second try rechecking if Mobile Data is available or not.
  • @Rahulrr2602 yes if there isnt any solution im planning to go for this
  • let me give a try
  • Using registerDefaultNetworkCallback, you won't know before hand. Alternatively, you can register two separate callbacks, one for TRANSPORT_WIFI, and other for TRANSPORT_CELLULAR. That ways you will have reference to both Networks if they are available. Most of the OEMs always keep Cell network active in the background. In case they do not, you can request Cell network by using CM#requestNetwork.
  • wat happens when mobiledata is connected while receiving network notification for wifi turned down
  • @Jeeva isConnected flag initialized inside onCreate method using online utility function, and isConnected flag will judge between old and current status onReceive action.
  • @Jeeva You can post your end call stuff using Handler with delay for switching between Wifi and mobile data, As @azizbekian answer mentioned.