Search code examples
javaandroidmultithreadingandroid-internet

Check internet in background - Android


I have been doing some research and seen some debate of whether to use Broadcast Receiver or Alarm Manager, Im not sure what to use but here is what I am trying to do and have done.

I have a method that will check if there is internet connection. And then updates the UI accordingly.

public void isNetworkAvailable() {
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected()) {
        mLayout.removeView(noInternetView);
        checkInternetViewOpen = false;
    } else {
        if (!checkInternetViewOpen) {
            checkInternetViewOpen = true;
            mLayout.addView(noInternetView, params);
        }
    }
}

And while I am in an activity that will be using the internet I want to run this once every few seconds to make sure the internet is still active. Like this

while (usingInternet) {
    //I need to make it wait
    isNetworkAvailable();

}

I also need to be not on the main thread for this, so I can make it wait, and then I will adjust the updating the UI parts on the main tread.

So how can I make this on a background thread? And what option should I use?

Thanks for the help in advance.


Solution

  • You can create a background thread to check for this task. Here are my sample code.

    The only things left for you to do is to fulfill setNetworkAvaiableUI(), setNetworkNotAvaiableUI(), and set NETWORK_CHECK_INTERVAL.

    private boolean isCheckNetworkThreadActive = false; // Flag to indicate if thread is active
    private boolean isNetworkAvaiableUIActive = false; // Flag to indicate which view is showing
    final private static int NETWORK_CHECK_INTERVAL = 5000; // Sleep interval between checking network
    
    @Override
    protected void onResume() {
        // Start network checking when activity resumes
        startCheckNetwork();
        super.onResume();
    }
    
    @Override
    protected void onPause() {
        // Stop network checking when activity pauses
        stopCheckNetwork()
        super.onPause();
    }
    
    private void setNetworkAvaiableUI() {
        // If network avaible UI is not showing, we will change UI
        if (!isNetworkAvaiableUIActive) {
            isNetworkAvaiableUIActive = true;
            runOnUiThread(new Runnable() {
                public void run() {
                    // Update UI here when network is available.
                }
            });
        }
    }
    private void setNetworkNotAvaiableUI() {
        // If network avaible UI is showing, we will change UI
        if (isNetworkAvaiableUIActive) {
            isNetworkAvaiableUIActive = false;
            runOnUiThread(new Runnable() {
                public void run() {
                    // Update UI here when network is unavailable.
                }
            });
        }
    }
    
    private void startCheckNetwork() {
        // Only one network checking thread can be run at the time.
        if (!isCheckNetworkThreadActive) {
            isCheckNetworkThreadActive = true;
    
            Thread checkNetworkThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (isCheckNetworkThreadActive) {
                        if (isNetworkAvailable()) {
                            // Set UI if notwork is available
                            setNetworkAvaiableUI();
                        } else {
                            // Set UI if notwork is not available
                            setNetworkNotAvaiableUI();
                        }
    
                        // Sleep after finish checking network
                        try {
                            Thread.sleep(NETWORK_CHECK_INTERVAL);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            checkNetworkThread.setName("Check Network Thread");
            checkNetworkThread.start();
        }
    }
    
    private void stopCheckNetwork() {
        // This will break while loop of network checking thread.
        isCheckNetworkThreadActive = false;
    }
    

    You can also make the code a lot shorter by using Timer and Handler, that are the options.