I need some way to detect when the network connection has been lost.
So a switch between mobile and wifi doesn’t really matter it’s just to detect at runtime when the connection has been lost.
I now have found some code which works fine for me.
public class ConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(ConnectivityReceiver.class.getSimpleName(), "action: "
+ intent.getAction());
}
}
I want to check inside the onReceive() method wheter or not a connection is still available or not.
The thing is, that I want to show a message to the user, if it has been lost. So what’s the best way of passing back to my Activity, that the connection has been lost?
If you want to track network connection state only when activity is on screen you can place your
ConnectivityReceiveras inner nested class inActivity. In this case you should register it inonResumemethod and unregister it inonPause. It will look like this: