I want to check the internet connection with a particular website before starting a method in my onClick. After doing some research I found this link who's accepted answer showed me how to do that Android Internet connectivity check better method the problem is though the method produces error android os networkonmainthreadexception, I did more research and found out that such an operation was required to be run in async task. How can I do this and still use the result in my button onClick method.
This is my current code in onCreate
.
@Override
public void onClick(View view) {
if (isInternetAvailable("18.184.67.80", 443, 1000)) {
Method() ;
} else {
Toast.makeText(getApplicationContext)) , "Internet not available" ).show;
}
}
Below is the code for checking internet connection with site
public boolean isInternetAvailable(String address, int port, int timeoutMs) {
try {
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress(address, port);
sock.connect(sockaddr, timeoutMs); // This will block no more than timeoutMs
sock.close();
return true;
} catch (IOException e) {
return false;
}
}
How would I use the above code in an async task and use results as to whether there is no internet connection or not in the if statement in the oncreate method?
Earlier on I also found this How to check internet access on Android? InetAddress never times out but I don't understand what code I would use to derive the results from the async task and use them in the oncreate under onClick.