Broadcast receiver for checking internet connection in android app

后端 未结 21 3191
温柔的废话
温柔的废话 2020-11-21 22:28

I am developing an android broadcast receiver for checking internet connection.

The problem is that my broadcast receiver is being called two times. I want it to get

21条回答
  •  鱼传尺愫
    2020-11-21 22:38

    This only checks if the network interface is available, doesn't guarantee a particular network service is available, for example, there could be low signal or server downtime

      private boolean isNetworkInterfaceAvailable(Context context) {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        }
    

    if you want to make a real connection to make sure your connection can gather data from a server or any url:

      private boolean isAbleToConnect(String url, int timeout) {
            try {
                URL myUrl = new URL(url);
                URLConnection connection = myUrl.openConnection();
                connection.setConnectTimeout(timeout);
                connection.connect();
                return true;
            } catch (Exception e) {
                Log.i("exception", "" + e.getMessage());
                return false;
            }
        }
    

    This function needs to be wrapped in a background thread :

    final String action = intent.getAction();
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                checkConnectivity(context);
            }
        }
    
    
        private void checkConnectivity(final Context context) {
            if (!isNetworkInterfaceAvailable(context)) {
                Toast.makeText(context, "You are OFFLINE!", Toast.LENGTH_SHORT).show();
                return;
            }
    
            final Handler handler = new Handler();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final boolean isConnected = isAbleToConnect("http://www.google.com", 1000);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (isConnected)
                                Toast.makeText(context, "You are ONLINE!", Toast.LENGTH_SHORT).show();
                            else
                                Toast.makeText(context, "You are OFFLINE!", Toast.LENGTH_SHORT).show();
                        }
                    });
    
                }
            }).start();
    
        }
    

    Add required permissions:

    
            
    

    Add this line under application in manifest file:

    android:usesCleartextTraffic="true"
    

    Add receiver to manifest file:

    
                
    
                    
                
                
    

    Register/Unregister the BR in you Activity:

    @Override
        protected void onStart() {
            super.onStart();
            IntentFilter filter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
            registerReceiver(connectivityChangeReceiver, filter);
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            unregisterReceiver(connectivityChangeReceiver);
        }
    

    this is the entire Broadcast class :

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.Handler;
    import android.util.Log;
    import android.widget.Toast;
    
    import java.net.URL;
    import java.net.URLConnection;
    
    public class ConnectivityChangeReceiver extends BroadcastReceiver {
    
    
        @Override
        public void onReceive(final Context context, final Intent intent) {
    
            final String action = intent.getAction();
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                checkConnectivity(context);
            }
        }
    
    
        private void checkConnectivity(final Context context) {
            if (!isNetworkInterfaceAvailable(context)) {
                Toast.makeText(context, "You are OFFLINE!", Toast.LENGTH_SHORT).show();
                return;
            }
    
            final Handler handler = new Handler();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final boolean isConnected = isAbleToConnect("http://www.google.com", 1000);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (isConnected)
                                Toast.makeText(context, "You are ONLINE!", Toast.LENGTH_SHORT).show();
                            else
                                Toast.makeText(context, "You are OFFLINE!", Toast.LENGTH_SHORT).show();
                        }
                    });
    
                }
            }).start();
    
        }
    
        //This only checks if the network interface is available, doesn't guarantee a particular network service is available, for example, there could be low signal or server downtime
        private boolean isNetworkInterfaceAvailable(Context context) {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        }
    
        //This makes a real connection to an url and checks if you can connect to this url, this needs to be wrapped in a background thread
        private boolean isAbleToConnect(String url, int timeout) {
            try {
                URL myUrl = new URL(url);
                URLConnection connection = myUrl.openConnection();
                connection.setConnectTimeout(timeout);
                connection.connect();
                return true;
            } catch (Exception e) {
                Log.i("exception", "" + e.getMessage());
                return false;
            }
        }
    } 
    

提交回复
热议问题