Rajesh kumar
Rajesh kumar

Reputation: 131

what is the best way to check Internet connection continuously in android

I am developing an application. In that one screen check Internet connection, immediately after onCreate() method. If network connection is good i am calling one AsyncTask class for load countries list and show it on screen in spinnerView. If there is no network connection i am showing Toast Message to User and call check_Network(AsyncTask). In this class protected Long doInBackground(URL... params) method i'm checking Network connected or not if connected call countries AsyncTask otherwise again i am calling check_Network(AsyncTask). this process repeat until network is connected. my problem is It is correct way for Check Network Repeatedly. please suggested me. sorry i am poor in english please understand.blow i am 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;
        }
    }

Upvotes: 3

Views: 2474

Answers (2)

Anupam
Anupam

Reputation: 887

Add below code in manifest, for adding receiver with connectivity 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" />

And at receiver side, get extras associated with intent and check for status. So whenever there is change in network status, you will be notified 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 would like to add permission in manifest and register receiver in your activity.

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

Make sure to unregister it as well before leaving activity with

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 based upon your requirement that you requires connected status only one time. First check for connectivity and if not connected then only register receiver.

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

Upvotes: 8

Saket Mittal
Saket Mittal

Reputation: 3886

To access internet we need INTERNET Permission
To detect network status we need ACCESS_NETWORK_STATE Permission

Add these lines in your AndroidManifest.xml:

<!-- Internet Permissions -->
    <uses-permission android:name="android.permission.INTERNET" />

<!-- Network State Permissions -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Create this method in your java class:

public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null) 
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null) 
                  for (int i = 0; i < info.length; i++) 
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }

          }
          return false;
    }

When ever you want to check Internet Status in your application call isConnectingToInternet() function and it will return true or false

ConnectionDetector cd = new ConnectionDetector(getApplicationContext());

Boolean isInternetPresent = cd.isConnectingToInternet(); // true or false

Upvotes: 1

Related Questions