Search code examples
androidandroid-activityandroid-broadcastreceiver

Android Check Internet connection continuously


I want to check internet connection continuously on every activity with the broadcastreceiver. I already write the code and it perfectly working. But I want to use it in every activity. How can I modify this code?

public class MainActivity extends Activity {



private static final String LOG_TAG = "CheckNetworkStatus";
 private NetworkChangeReceiver receiver;
 private boolean isConnected = false;
 private TextView networkStatus;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

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

  networkStatus = (TextView) findViewById(R.id.networkStatus);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

 @Override
 protected void onDestroy() {
  Log.v(LOG_TAG, "onDestory");
  super.onDestroy();

  unregisterReceiver(receiver);

 }


 public class NetworkChangeReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(final Context context, final Intent intent) {

   Log.v(LOG_TAG, "Receieved notification about network status");
   isNetworkAvailable(context);

  }


  private boolean isNetworkAvailable(Context context) {
   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) {
       if(!isConnected){
        Log.v(LOG_TAG, "Now you are connected to Internet!");
        networkStatus.setText("Now you are connected to Internet!");
        isConnected = true;
        //do your processing here ---
        //if you need to post any data to the server or get status
        //update from the server
       }
       return true;
      }
     }
    }
   }
   Log.v(LOG_TAG, "You are not connected to Internet!");
   networkStatus.setText("You are not connected to Internet!");
   isConnected = false;
   return false;
  }
 }


}

Solution

  • I want to use it in every activity. How can I modify this code?

    Create a BaseActivity class which extends AppCompatActivity, and then make all of your Activity classes extend this BaseActivity class. Put your code to check internet connection in the BaseActivity class. cheers :)