Search code examples
androidbroadcastreceiver

BroadcastReceiver (To check internet connectivity) getting called at the start of activity


I am using BroadcastReceiver to check internet connectivity but it is getting called at the start of activity. This is my BroadcastReceiver

public BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, Intent intent) {
            connectivityManager = (ConnectivityManager)
                    context.getSystemService(Context.CONNECTIVITY_SERVICE );
            activeNwInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            boolean isWifiConnected = activeNwInfo != null && activeNwInfo.isConnectedOrConnecting();
            activeNwInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            boolean isMobileNwConnected = activeNwInfo != null && activeNwInfo.isConnectedOrConnecting();
            try {
                if (isWifiConnected || isMobileNwConnected) {
                    Snackbar.make(cordinatorlayout, "Connection established", Snackbar.LENGTH_INDEFINITE)
                            .setAction("GO ONLINE", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    //Toast.makeText(context, "clicked", Toast.LENGTH_SHORT).show();
                                    finish();
                                    startActivity(getIntent());
                                }
                            }).show();
                }else {
                    Snackbar.make(cordinatorlayout, "You are Offline", Snackbar.LENGTH_INDEFINITE).show();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    };
` and I have registered BroadcastReceiver inside oncreate() of MainActivity. My BroadcastReceiver is getting called but it is getting called at the start of activity.

Solution

  • It initially gets called once when you set up a BroadcastReceiver. Afterwards, it starts to listen to changes in the Internet connectivity status, and called each time the status is changed.

    If you want it to be called only when the Internet connection changes from DISCONNECTED to CONNECTED, create a variable that holds the current status. When you receive CONNECTED in your receiver, check if the variable is DISCONNECTED. If so, do whatever you want; otherwise, do nothing.