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!
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With