0

I'm already using the code below to detect if the user is connected to the internet at the application's splash screen, but I need to detect this whenever the user is in a specific activity. Imagine you are using turn-by-turn navigation and you depend on internet connection, so you must detect a broken internet connection when it happens.

How can I do this without slowing down the app with an infinite loop?

private boolean isOnline(Context context) {
    try {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = cm.getActiveNetworkInfo();

        return (networkInfo != null && networkInfo.isConnected());
    } catch (Exception exc) {
        return false;
    }
}
juliano.net
  • 7,982
  • 13
  • 70
  • 164

2 Answers2

0

I belive you shoul write your own service with PhoneStateListener, you should implement this method public void onDataConnectionStateChanged(int state) {} And from this service you can check in any time if there is DataConection.

Here is an article about Android PhoneStateListener Illustration–with Auto Logging Calls to Google Calendar Example

Roman Nazarevych
  • 7,513
  • 4
  • 62
  • 67
0

You should use a BroadcastReceiver do to so:

Here are few references for this you can get better idea about this with example.

Reference 1

Reference 2

Reference 3

Thanks,

Community
  • 1
  • 1
Pratik Sharma
  • 13,307
  • 5
  • 27
  • 37