Check your internet connection in my entire application.

I am working on an internet application, so I need to monitor my internet connection. link

I used this code to create mainActivity to check my internet connection, it works great.

public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); return cm.getActiveNetworkInfo().isConnectedOrConnecting(); } 

But I need this monitoring to be done through the application. Where should I use this? Need any asynchronous program?

+4
source share
2 answers

Create a BroadcastReceiver to detect changes in connection status. see Eric answer here

+6
source

Use BroadCast Receiver, for example:

 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false); NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO); // do application-specific task(s) based on the current network state, such // as enabling queuing of HTTP requests when currentNetworkInfo is connected etc. } }; 

  private void registerReceivers() { registerReceiver(mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } 
+4
source

Source: https://habr.com/ru/post/1380687/


All Articles