Detecting loss of WiFi connection in OkHttp3 - android

When OkHttp3 calls the onFailure callback, it passes an IOException. Is there a specific subclass of IOException that will indicate that the target device has disappeared from the WiFi network? Is there another way to detect this?

IOException has several sub-classes; while it may be save to assume that something went offline - because when the own network connection is still alive, it has to be the other side of the connection. when it throws an IOException, that's an IOExcpetion; casting it won't add any more information.
the state of the own network connection can be detected, but not with OkHttp3. here's an example for that on my GitHub; see class ConnectivityListener and class ConnectivityReceiver.
How would you detect the state of another host's network connection?
this can be tested, by switching off the WiFi network of either device; both situations would cause an IOException.

Related

Android TRANSPORT_CELLULAR network not available if wifi is connected. How do we make it available?

The moment I get on a wifi connection, the cellular network is completely lost even though the cellular network indicator is definitely on.
This is my network request
val request = NetworkRequest.Builder().run {
addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
build()
}
connectivityManager.registerNetworkCallback(request, callback)
I've tried looking in the connectivityManager.allNetworks list and it's no where to be found. Only the wifi network is in there.
What's even weirder is there is one other cellular network that is always there. It does not have the same ID as my cellular network. There's no connection that can be made with it. It never shows up with registerNetworkCallback. The capabilities on it always include "valid" and "internet"
What am I seeing here? Why is my cellular network lost? What is this phantom cellular network?
targetSdkVersion: 29
Device: Galaxy S10 - Android 12
I figured this out.
If you call registerNetworkCallback the above will happen, but if you call requestNetwork with TRANSPORT_CELLULAR,
connectivityManager.requestNetwork(request, callback)
Android will keep the cellular network around. I was so confused because the documentation was so lacking. Once you do that, it will ask you to add the CHANGE_NETWORK_STATE permission.
After this step, the network is available, but you won't be able to make any request with it. You have to call
connectivityManager.bindProcessToNetwork(theCellularNetwork)
to get any connection.
After this is done, the cellular network can be used in tandem with the wifi network. You can even send some traffic to one and some to the other. If you use OkHttp like I do, you just bind the client with the network's socketFactory
val client = OkHttpClient().newBuilder().run {
socketFactory(network.socketFactory)
build()
}
client.newCall(
Request.Builder().url("https://example.com").build()
).execute().let {
Log.i(TAG, "Fetched ${it.body!!.string()}")
}
The cellular network isn't lost, but your app isn't allowed to use it. Once WiFi is connected, everything is forced to use that connection. The only exception to this rule is if your phone has a feature called "Dual Acceleration", which allows the cellular connection to stay active (and obviously, the user would have to enable that feature). Alternatively, you may have a setting in your phone's Developer Options called "Cellular Data Always Active", which will do the same thing.
But needless to say, you can't rely on either of those 2 features being enabled in a production environment. So, just assume that when WiFi is connected, that's the only connection that your app can use

SocketIo EngineIOException cause: SSLException

I get this exception on Android using SocketIo, everytime when internet gets disconnected (I turn off wifi). I cant find the reason, please help :
This is exception is to be expected any time an SSLSocket read fails due to an unavailable network. Socket.IO clients may safely ignore it.
As you might expect, disabling a network while you are using it causes I/O errors. In Java, this produces an IOException of one kind or another. If you had been using "normal" sockets, this would have been a SocketException, and you would have seen the same sort of message ("software caused connection abort"). Since, in this case, you are using an HTTPS connection, the IOException is an SSLException (which wraps the error encountered by the lower-level TCP socket).
Any IOExceptions thrown by the TCP socket will cause SSLExceptions on the SSLSocket, at least until such time as the SSLSocket is properly closed.

Android - What´s the difference between WifiManager disableNetwork() and disconnect()

What´s the main difference between the WifiManager disableNetwork() and disconnect() method?
If I´m not guessing wrong, the disconnect() method makes it candidate for a reconnect when it enters inside the visibility of the wifi hotspot but disableNetwork() don't.
public boolean disableNetwork (int netId). Disable a configured network. The specified network will not be a candidate for
associating. This may result in the asynchronous delivery of state
change events.
public boolean disconnect () Disassociate from the currently active access point. This may result in the asynchronous delivery of
state change events.
I´ve a Wiko Darkmoon (Android 4.2.2) device for testing purposes and when I call disconnect() it reconnects some seconds later to the same wifi point without taking in mind higher priority networks neither the quality of the signal.
So my questions are:
What's the difference between disableNetwork() and disconnect() method?
It´s my guess right?
It´s the Wiko's implementation the right one or it´s the one misfiring?
When roaming between two wifi spots with same SSID and after calling disconnect() will it filter by SSID or MAC for the reconnect?
Thanks
disconnect() as name suggests just disconnects the device from current Wi-Fi network. If the device connects later to the same or another network is dependent on the device settings and is completely unrelated to the method call.
disableNetwork(int) will prevent automatic connection to the specified network.

UnknownHostException in android : Wifi issue

I have get UnknownhostException in parsing JSON data from server,
My URL working on :
http://jsonlint.com
on real device browser(data plan only)
Sometimes its working on PC browser and sometimes not.
Actually I have get the wifi issue, Sometimes its working on wifi connection, when its not, I have restarted my wifi and its worked, and after some time the same issue came,
I want to get the permanent solution for this wifi connection issue, Restarting the Wifi is never a solution on the application user side,
What is the exact problem and solution also...
Usually the UnknownHostException fires when you cannot resolve the DNS record of the URL you've provided. There's a reasonable timeout for that operation, but if you have a weak WiFi connection or you don't have enough signal on your device, the communication can be interrupted in the middle between sending and receiving the response, so your device doesn't receive the response, thus it thinks it's a DNS timeout.
There are 2 things you can try:
Increase the timeout of the response. This will not help, though, if your communication gets interrupted you already sent the query.
Use the IP address instead:
shut-up#i-kill-you:~$ ping jsonlint.com
PING jsonlint.com (54.243.171.164) 56(84) bytes of data.
WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
int linkSpeed = wifiManager.getConnectionInfo().getRssi();
System.out.println("Link Speed is======"+linkSpeed);
It will give u wifi speed so just mention one speed if that speed come then only do next work

In Android how do I disconnect a socket?

So I've got a socket that is connected to an outside web address and when it gets a certain message it's supposed to disconnect. I tried calling socket.close() but socket.isConnected() is still true. No luck searching for an answer
isConnected() only tells you if you made a successful connection to a socket. isClosed() tells you if you called close().
Check out this guys response https://stackoverflow.com/a/3701249/2453771
" When you use Socket(), which you seem to have overlooked,
Socket.isConnected() tells you whether Socket.connect() has been
called or not. Similarly for isClosed() and close().
Confusion over these methods results from confusing the state of the
socket, which is under the control of the application, with the state
of the overall connection, which is under the control of the protocol.
isConnected() and isClosed() tell what you have done to the socket.
There are no APIs other than read and write for determining the state
of the connection."
Oracle documantion < in here it's well explained that once you call .close() the connection is closed and you can check by isClosed().
.close() :
Closes this socket.
Any thread currently blocked in an I/O operation upon this socket will
throw a SocketException.
Once a socket has been closed, it is not available for further
networking use (i.e. can't be reconnected or rebound). A new socket
needs to be created.
isConnected() and isClosed() tell you the current state of your socket (in your side).
isConnected() tells you whether you have connected this socket and isClosed() tells you whether you have closed this socket. Until you have, it returns false.
Yes, right. It surely seems socket.close() and socket.isConnected() are independent from each other. I wish method naming was not as confusing.
From official Android SDK:
public boolean isConnected()
Returns the connection state of the socket.
Note: Closing a socket doesn't clear its connection state, which means
this method will return true for a closed socket
P.S. more intuitively it should be called wasConnected() 😅
http://developer.android.com/reference/java/net/Socket.html#close()
Do a checksum on the data returned, make sure you get the correct value. If so and you called close and try-catch everything, it should be fine.
You could watch in a debugger and make sure nothing is leaking.
try
socket.isClosed()
Returns a boolian, whether this socket is closed.
Refer
Sockets

Categories

Resources