Check your internet connection at runtime

Good afternoon, I have an application with two actions: the main and the detailed page.

When there is an Internet connection, the user can go from the main page to the details page. When there is no internet connection, he cannot do this.

The problem is this: when I talk in detail about the page and turn off Wi-Fi, I would like to complete this work, how can I implement this functionality? I checked in the main activity class something like this:

 private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

It works fine when I launch the application over the Internet or without it, but when I turn off Wi-Fi at runtime, it does not work.

Anyway, thanks!

+4
source share
3 answers

ConnectivityManager CONNECTIVITY_ACTION ( "android.net.conn.CONNECTIVITY_CHANGE" ). , ( ) .

, , , , .

public class InternetReceiver extends BroadcastReceiver {

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

    if (isConnected()) 
        Log.d("NetReceiver", "Internet is connected");  
    else
        Log.d("NetReceiver", "Internet is not connected");    
   }   
};

-, 3g

public boolean isConnected() {

Runtime runtime = Runtime.getRuntime();
try {

    Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
    int exitValue = ipProcess.waitFor();
    return (exitValue == 0);

  } catch (IOException e)          { Log.e("ERROR", "IOException",e); } 
    catch (InterruptedException e) { Log.e("ERROR", "InterruptedException",e); }

return false;
}

:

<receiver android:name=".InternetReceiver">
<intent-filter>
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>

+5

, , , . .

+3

:

  • , .
  • Runnable
  • run() Thread Runnable
  • onCreate() MainActivity Thread Runnable n /
0

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


All Articles