Broadcast receiver for checking internet connection in android app

后端 未结 21 3181
温柔的废话
温柔的废话 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:48

    Add permissions:

    
     
    

    Create Receiver to check for connection

    public class NetworkChangeReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(final Context context, final Intent intent) {
    
            if(checkInternet(context))
            {
                Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show(); 
            }
    
        }
    
        boolean checkInternet(Context context) {
            ServiceManager serviceManager = new ServiceManager(context);
            if (serviceManager.isNetworkAvailable()) {
                return true;
            } else {
                return false;
            }
        }
    
    }
    

    ServiceManager.java

    public class ServiceManager {
    
        Context context;
    
        public ServiceManager(Context base) {
            context = base;
        }
    
        public boolean isNetworkAvailable() {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.isConnected();
        }
    }
    

提交回复
热议问题