Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check internet connection at runtime

Tags:

android

Good Day, I have an app with 2 activities: main and details page.

When there is internet connection user can navigate from main to details page. When no internet connection he can`t do that.

The problem is: When I`m in details page and switch off wifi I would like to finish this activity, how can I implement this functionality? I have check in main activity class something like that:

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

It`s works fine when I start the app with internet or without that, but when I switch off the wifi at runtime it doesn`t works.

Anyway, thank you!

like image 222
Vadim L. Avatar asked Sep 07 '15 11:09

Vadim L.


2 Answers

You have to Monitor for Changes in Connectivity

The ConnectivityManager broadcasts the CONNECTIVITY_ACTION ("android.net.conn.CONNECTIVITY_CHANGE") action whenever the connectivity details have changed. You can register a broadcast receiver in your manifest to listen for these changes and resume (or suspend) your background updates accordingly.

Whenever internet state changes, your broadcast receiver will be called, and if the internet disconnects then you can handle it accordingly.

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");    
   }   
};

This method checks for connections from all internet sources, including 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;
}

In your manifest file add this:

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

Here is the Source

like image 86
Sharp Edge Avatar answered Oct 01 '22 12:10

Sharp Edge


You may want to implement a broadcast receiver listening to the Event of connection termination, so that you can immediately take action and finish the detail activity. this link may help.

like image 28
Hosein Hamedi Avatar answered Oct 01 '22 14:10

Hosein Hamedi