Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

Android listen to network change

ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
    @Override
    public void onAvailable(Network network) {
        // network available
    }

    @Override
    public void onLost(Network network) {
        // network unavailable
    }
};

ConnectivityManager connectivityManager =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    connectivityManager.registerDefaultNetworkCallback(networkCallback);
} else {
    NetworkRequest request = new NetworkRequest.Builder()
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
    connectivityManager.registerNetworkCallback(request, networkCallback);
}
Comment

Android listen to network change

val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager?.let {
    it.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {
            //take action when network connection is gained
        }
        override fun onLost(network: Network?) {
            //take action when network connection is lost
        }
    })
}
Comment

PREVIOUS NEXT
Code Example
Java :: java take and save screenshot 
Java :: hashmap put method 
Java :: string compareto vs equals java 
Java :: search 
Java :: java math random 
Java :: what is a float java 
Java :: djava days between two dates 
Java :: greatest of three in java 
Java :: insert in arraylist 
Java :: how to change fragment on button click navigation drawer 
Java :: java string util if empty default 
Java :: kotlin spinner default value 
Java :: generate objects with for loop java 
Java :: Java Access superclass attribute 
Java :: json java 
Java :: Syntax of Creating Java Map Objects 
Java :: java creating an object 
Java :: get string size on screen 
Java :: binary tree traversal 
Java :: intent class for url and phone and others 
Java :: Declaring a Java Method 
Java :: Error: Could not find or load main class Hello Caused by: java.lang.ClassNotFoundException: Hello studio visual code 
Java :: Split string into a string array 
Java :: properties object using a file 
Java :: how to sort linked list in java 
Java :: jdsu software download 
Java :: JAVA Declaration Statements 
Java :: jkora 
Java :: view binding 
Java :: how to create arraylist in java 
ADD CONTENT
Topic
Content
Source link
Name
5+4 =