Java connection state active checking (ping)
Showcase, July 1, 2020 - 5:03pm, 914 views
The basic way to control the data connection state in Java is to register a BearerControlListener instance.
This demo I got from a colleague shows the alternative or complementary way to detect possible problems in data transmission. For instance in case BearerControlListener still shows the conneciton but data sending is actually not possible due to a very poor signal quality.
Please note that this solution uses ICMP Echo Requests (Ping) which consumes data from the user data plan. And of course it uses up some resources like RAM, processing power, threads etc.
The Heartbeat class is for checking the connection status in a specific interval, and indicating when connection is lost, or established.
This class makes a new thread, which uses the Ping class to provide the checking of the connection.
In the meantime the main thread of Heartbeat class is counting the time to the next attempt of checking connection, and updating the current state of connection.
Every time when the connection status is changed, the callback function from the set listener is called - the HeartbeatEvent method from HeartbeatEventListener.
On start, the connection state is assumed as disconnected.
If connection is established but ping's timeout isn't expired - the Ping method is still waiting for a response - but Heartbeat's timer expires and the failedCounter increments.
In case when connection (contekst/barrer) can not be established (e.g. antenna issue) the Ping method is trying open a connection, and when it isn't possible, the Ping hangs longer than the configured timeout.
Then Heartbeat's thread is still counting the time, and when the timer expires, the ping attempt is considered as failed, and failedCounter increments.
If failedCounter is equal to maxFailedAttempts, the connection is considered lost. The failedCounter will no longer increment.
When the pinging succeeds the connection is considered as established correctly and failedCounter is reset.
The stop method is breaking the main loop in Heartbeat class, no later than after 1 second.
Heartbeat class using a Ping method from com.cinterion.misc.NetExtension. The Ping method used in Heartbeat will automatically start a data connection if it is active. If there is no active connection, the Ping method will try to establish a new connection.
The package includes Heartbeat class and the usage example.