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;
    }
}
4

2 回答 2

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

于 2013-01-20T12:56:07.970 回答
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,

于 2013-01-20T13:01:27.173 回答