Checking if the internet connection is lost at runtime

Darthcow :

Good day. I know how to check if there is an internet connection available, my problem is that I want to present the user an AlertDialog that prevents action except trying again whenever the connection is lost or deactivated. What I don't know is how to code it only one time, so I don't need to replicate it manually in all activities.

I tried using Observer Pattern, and initialize it in SplashActivity(Launcher Activity).


 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        ObservedObject observedObject = new ObservedObject();
        observedObject.addObserver(new ObserverInternetConnection());

}
 public class ObservedObject extends Observable {
        private boolean isConnected;

        public boolean isConnected() {
            return isConnected;
        }

        public void setConnected(boolean connected) {
            isConnected = connected;
            setChanged();
            notifyObservers();
        }

     public class ObserverInternetConnection implements Observer {

        @Override
        public void update(Observable observable, Object o) {
            if (observable instanceof ObservedObject) {
                if (observable.hasChanged())
//alert is a method to show toast message
                    alert("connection changed");
                if (((ObservedObject) observable).isConnected)
                    alert("connected");
                else
                    alert("disconnected");

            }

        }
    }

It worked when I manually set the observedObject connection. But I want to avoid doing so. Is there a way to do this automatically? I was thinking of using another thread, but how could I do so? another problem is that the way i check the internet connection is using ConnectivityManager but it need me to pass the context and the context can (and will) change throughout the application, how can I overcome so? Is there any other approach for the problem?

Antonis Radz :

I would suggest to create BaseActivity where you are initializing connectivity change listener (Observer in your case) and extend this activity with Splash, Main and other activities that you are using.

This way you are going to avoid code duplication.

Also don't forget to unregister listeners when activity is destroyed.

Also you dont need to use different threads. Here is example how to listen connectivity changes in Activity:

Register receiver first:

   @Override
    public void register(Context context) {
        initReceiver();
        final IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(receiver, intentFilter);
    }

receiver

receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (isOnline()) {
                    hideNoConnectionError();
                } else {
                    showNoConnectionError();
                }
            }
        };

and isOnline()

 val isOnline: Boolean
        get() {
            return try {
                val connectivityManager = context.getSystemService(
                        Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                connectivityManager.activeNetworkInfo != null &&
                        connectivityManager.activeNetworkInfo.isConnected
            } catch (exception: Exception) {
                false
            }
        }

sorry, last method is written in Kotlin, but I think it is completely understandable

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=308698&siteId=1