Java – What is the best way to continuously check internet connection in android

What is the best way to continuously check internet connection in android… here is a solution to the problem.

What is the best way to continuously check internet connection in android

I’m working on an app. In that screen, check the Internet connection immediately after the onCreate() method. If the network connection is good, I’ll call an AsyncTask class to load the list of countries and display it on the spinnerView’s screen. If there is no network connection, I will display a toast message to the user and call check_Network (AsyncTask). In such protected Long doInBackground(URL… params) method, I’m checking if the network is connected and calling country AsyncTask if it is, otherwise I’ll call check_Network(AsyncTask) again. Repeat this process until you are connected to the network. My question is that this is the right way to double-check the network. Please advise me. Sorry, my English is poor, please understand. I’m showing my code

if (CheckNetwork.isOnline(this)) {
            try {
                new CountryProcess().execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {

Toast.makeText(
                    getApplicationContext(),
                    getString(R.string.network_connection_fail)
                            + "!", Toast.LENGTH_LONG).show();
            new NetWork_connectivity().execute();
}

//.......................//

class NetWork_connectivity extends AsyncTask<URL, Integer,Long>
    {
        @Override
        protected Long doInBackground(URL... params)
        {
            if (CheckNetwork.isOnline(MainActivity.this)) {

new CountryProcess().execute();

}else
            {
                new NetWork_connectivity().execute();
            }

return null;
        }
    }

Solution

Add the following code to the list to add a sink with the connection change intent

<receiver android:name=". NetworkStateReceiver">
   <intent-filter>
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
   </intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

On the receiving side, get additional information about the intent and check the status. Therefore, whenever the network status changes, you will be notified and then perform your task accordingly.

public class NetworkStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
 super.onReceive(context, intent);
 if(intent.getExtras()!=null) {
    NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
    if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
        connected
    }
 }
 if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
        not connected
 }
}
}

For your case, you want to add permissions to the list and register recipients in your activity.

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(networkReceiver, filter);

Make sure to unregister before leaving the activity

unregisterReceiver(networkReceiver);

private BroadcastReceiver networkReceiver = new BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
     super.onReceive(context, intent);
     if(intent.getExtras()!=null) {
        NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
        if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
            connected
        }
     }
     not connected 
   }
}

And according to your requirements, you only need to connect the status once. Check the connection first, and only register the sink if it is not connected.

public boolean isNetworkConnected() {
        ConnectivityManager cm =
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

Related Problems and Solutions