Doing something just BEFORE wifi disconnection - android

I understand that on a wifi network there are sudden disconnections which prevent me from sending messages to my server.
But sometimes there's still one last chance before the disconnection, for example if the signal is low or the user is trying to turn off the wifi. On those occasions I would like to send a logout message to my server.
How do I detect disconnections like those?
I tried to retrieve changes of connectivity by registering a broadcast listener:
registerReceiver(this,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
...
public void onReceive(Context context, Intent intent) {
NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if( (info.getState()== State.DISCONNECTING) && (info.getType() == ConnectivityManager.TYPE_WIFI) ) {
//send logout
}
But it looks like at that time it's already too late. My logout message doesn't go through.
Is there a better way?
[Update 1]
I also tried:
if( (info.getDetailedState()== DetailedState.DISCONNECTING) && connectionTypeOK ) {
[Update 2 - SOLUTION]
The solution is, as stated below, using a combination of receiving the RSSI_CHANGED_ACTION and WIFI_STATE_CHANGED_ACTION broadcasts to monitor the signal strength and the WIFI_STATE_DISABLING events respectively. When this happens, I send my logout request. This works exactly as I needed. Thanks!!

You could try to implement a variable "heartbeat" function, by using WifiManager to detect changes in signal strength. Here you can find some related code, btw.
Now, once you receive a RSSI_CHANGED notification, according to the corresponding signal strength, you will update the frequency of your app's "heartbeats" to the server: if the signal is strong, you will only need to notify the server infrequently that the app is alive. Once the signal becomes week, however, just like adrenaline kicking in for a real live being, so should your app notify the server more frequently. If the signal's strength recovers, you'll send a specific message to let the server know everything is all right again; if, however, the server does not receive this message in a certain period of time and the "heartbeat" stops - your app ceases notifications for that amount of time - then the server logs it out until receiving from it again.

If you're based on TCP connections, the server should know when a session disconnects unexpectedly - it will get an RST or FIN packet, depending on the router configuration between the client and server.
There's no need to do anything from the client's point of view - TCP connections are designed so you can know when they're interrupted.

Why don't you have the server regularly ping the client, at certain intervals, and just log out if it doesn't get a response? Trying to make this happen through client side will be cumbersome.

A better way is not to have sessions at all, if possible.
Why is it a problem if the user doesn't log out?

Maybe this is a long shot.. but why don't you use Google push notifications to start an activity if wifi is on. That would tell the server that the phone is "online". If that doesn't happen in X seconds or 1 minute ou whatever, redirect it to somewhere else.

I would implement a handler on the server that handles when the client is not able to receive a message. After each message the phone could send a message back to the server saying it successfully received the message.

are you looking for a good way for users to send / receive data after a disconnection?
HTML5 has a local storage (with a good file size too) so if a user is attempting a huge form, you first save it locally and then attempt to send it to server. if failed when the user loads the page again, you can first check if the file has some content, and if so, you can send that data, clear the content and proceed accordingly.
may be this will help you out http://www.html5rocks.com/tutorials/appcache/beginner/
or look at the local storage tutorial: http://www.youtube.com/watch?v=h0uZIljjElo
using this you could save frequent status data and modify it on the fly.
and Android should support HTML5 too.

Related

Save Response to Server When Network Connection goes OFF

I have two apps
Client App
and
Server App
in android
What i want
To check in my server app that weather client app has internet connection or not.
What i have done
I had read this post
I have used BroadcastReciever to Listen weather internet is available or not. All is well. When internet connection goes right , i am saving value online to Firebase "true"
But
When internet connection goes off ,
i am using Firebase onDisconnect() method to save ServerValue.TIMESTAMP
It works sometime in two minute but sometime it doesn't update firebase and value remains true.
Note what i want when client app is connected ,on firebase it should save true and when it is not connected it should save false . Though in my server app i will retreive those values to show to client is online or offline
is there any other technique to do such a scenario in android ?
What do you suggest any improvement in my current scenario. ?
Help will highly appreciated.
Thanks
leave this onDisconnect(), write an API that will do nothing but will just ping the server after a fixed time continuously, let's say after each 2 seconds the API will be called(through service), so in case the net is disconnected or the cell phone is even off, since API will not respond to the server, here you will write a code in case app did't ping to the server after 2 seconds(or you can say after 5 seconds), the response(online status) should be FALSE automatically!
so in case the app is again connected to internet, since the service is running so service will update your false into TRUE again
that's too simple!
i think this is your required function!

Amazon SQS (Android) handle intermittent network connectivity

I'm trying to figure out how to handle intermittent network connectivity in regards to Amazon SQS on Android. I need to send messages every 10 minutes (or so) and would like any messages that cannot be delivered due to network issues be sent at the earliest time when the network is restored. My hosted service orders messages so getting a few queued messages at once is no issue, but having messages be completely dropped is a problem.
AFAIK, my retry policy is set to retry up to 25 times and then give up. Obviously this is not a great solution, but I didn't see any hooks for network connectivity callbacks or any option to have it retry when the connection is restored if the cause of the error is due to network issues.
The only alternative I can think of (using what I know about this API) is to implement a VERY long-lasting back off strategy and hope the user gets network again with X amount of time, but that seems incorrect.
ClientConfiguration ccfg = new ClientConfiguration();
ccfg.setRetryPolicy(new RetryPolicy(null, null, 25, false));
AmazonSQSClient client = new
AmazonSQSClient(params[0].credentialsProvider, ccfg);
Setting the retry policy is not going to help you in this case.
What you might need to do is:
Cache sqs messages when network is not reachable on mobile.(either file or db).
Implement a network change listener on android and trigger sqs calls when the networks changes from unreachable to reachable.
Take a look at https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

How to start a method in the same time on 2 devices

I have 2 android phones phones, both connected to the same wifi, both with bluetooth.
I want some method that syncs somehow the phones and starts a function on the same time on both phones.
For example playing a song at the same time.
I already tried with bluetooth but its with lag, sometimes 0.5 secs. I want something in +- 0.01sec if possible.
Someone suggesting playing it in the future with 2-3 seconds, sending the time-stamp, but how do you sync the internal clocks of the devices then ?
Before calling that particular method, try to measure the latency between the two devices:
1.First device says Hi(store the current time)
2.Second device receives the Hi.
3.Second device says back Hi !!
4.First device receives the Hi.((storedTime - currentTime) / 2 )
Now you have the latency, send your request to second device to start your particular method and start it on first one after the latency.
Try to measure the latency 5 to 10 times to be more accurate.
you have a way to transfer data between the devices right ?
if so you can send a time-stamp which is in the future,
ex: if the present time stamp is 1421242326 you send 1421242329 or something and start the function at that time on both devices.
Basically use #Dula's suggestion (device 1 sends command to device 2 and gives a "start time" which lies in the future). Both devices then start the action at the same time (in the future).
To make sure that the devices are synchronized, you can use a server-based time sync (assuming that both devices have Internet access). To do this, each device contacts the same server (using NTP, or HTTP-based NTP, or contacts a known HTTP server, like www.google.com and uses the value in the "Date" header of the HTTP response). The "server-date" is compared to the system clock on the device, and the difference is the "time-offset from server-time". The time-offsets can be used to synchronize on the "server-time", which is then used as the time base for the actual action (playing the media, etc.).
If your WiFi router allows clients to talk to each other (many public hotspots disable this), you could implement a simple socket listener on one (or each) device and have the initiating device broadcast a message.
For more complicated things and network flexibility, I've had good success with connected sessions using AllJoin. There is a bit of a learning curve to do interesting things, but the simple stuff is pretty easy once you understand the architecture.
Use a server to provide a synchronous event to just the two clients who have decclared their mutual affinity (random as a parm and pair serializer Partner-1 or Partner-2 which they share prior to their respectve calls for the sync event).
Assume both clients on same subnet (packets from 2 events serialized on the server , arrive across the network at the 2 clients simultaneously client-side) This provides synchronous PLays by 2 , bound clients.
The event delivered by server is either a confirm to play queued selected track OR a broadcast( decoupled, more formal)
The only tricky thing is the server side algorythm implementing this:
Queue a pair of requests or error
Part1, part2 with same Random value constitute valid pair if both received before either times out.
On a valid pair schedule both to the same future event in their respective , committed responses.
OnSchedule do the actual IO for 2 paired requests. Respective packets will arrive back at respective clients at same time, each response having been subject to equal network latency
Ng if two diff carrier 4G or lte networks involved. (Oops)
This thing is possible via socket, you will send a event via socket then the other device receive that event. For learn socket io chat
maybe it's not the answer you are looking for but i think that due to the high precision you are wanting , you should look for a push technology, i advice you to take look at SignalR. It's real time technology which gives you abstraction of sending methods , it have a built-in methods like Clients.All.Broadcast that fit your needs.
You can try to use some MQTT framework to send message between two device, or into a set with more number of devices.

Lost messages with aSmack

i'm using aSmack in my Android app to receive messages from my Desktop-Jabber-client. This works fine and even if my android phone is offline (after the connection was closed properly) it will receive the offline messages after the next login.
But when i enter the airplane-mode on the phone or shutdown the phone so that the connection is abruptly closed (without calling disconnect() on the Connection-object) the phone stays "online" in the contact-list of my Desktop-Jabber-client for a while and i can send messages to it. However these messages never arrive. Even though the phone logs in to the server again. These messages are lost.
Does anyone know how to fix this issue? Losing messages in a chat is not an option. :)
EDIT: Added Test-Code
BroadcastReceiver: http://pastebin.com/cFLzGXgy
Service: http://pastebin.com/wLpQCQfT
The first one is a BroadcastReceiver starting the service (second URL) each time the phone is connected to a network.
PS: This is only a test-code! You must change the server/username/password if you want to use/test it.
You can try to send delivered message from client b to client A when the message arrival. The problem is if the client A is offline (no connection break) the delivered confirm don't send until the user receives the message and the client B can't re-send the message.
you can try to send acknowledgement of receiving the message using Smackx Message Events
this will assure the message is delivered else you take corrective action.
this problem occurs when your connection broke.
You need "Stream Management" XEP-198 enabled connections to achieve this messages. refer to this blog : http://op-co.de/blog/posts/XEP-0198/ Basically it allows for stanza acknowledgement and stream resumption, which is exactly what you want to do in case.so you should wait till smack will 4.1 release.

How to prevent the phone from losing IP traffic?

I have a simple app that periodically sends HTTP_GET requests to a server. When sending requests over 3G, I noticed that the requests sometimes time out (and the server-side logging shows that it NEVER receives the request either).
After trying out different combinations I found one consistant pattern when this problem occures (it times out after every 5-15 successful requests).
- TelephonyRegistry: notifyDataConnection() state=2isDataConnectivityPossible()true, reason=null
- TelephonyRegistry: broadcastDataConnectionStateChanged() state=CONNECTEDtypes=default supl, interfaceName=rmnet0
- NetworkLocationProvider: onDataConnectionStateChanged 3
According to Google, NetworkLocationProvider is changed to 'DATA_SUSPENDED', which implies "connection is up, but IP traffic is temporarily unavailable". (see TelephonyManager). On the situations where HTTP_GET requests succeeds, the state is changed to '8'. My app doesn't use the location manage and I've shut down every other non-critical app from running!
I want to know:
What is the cause of this issue? Why does the connection status go to DATA_SUSPENDED?
Is it possible to avoid/overcome this problem?
Any help/insight into this is much appreciated! Thanks in advance!
I have the same problem with my app running on an Huawei IDEOS X3 with Android 2.3.5. The app sends data each minute to a server using HttpClient.
Using logcat I can see that the data connection is lost and then reestablished after a short while. Previously my app stopped working since it tried to send data without a connection causing an exception which was not properly handed.
I don't know the reason for the intermittently dropped data connection but I now handle the situation by checking if there is a data connection prior to sending the data. In my case it does not matter if some data is never sent. If it was important to avoid data loss, I could buffer the data and send it once the connection was back.
public Boolean isDataConnection() {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
return tm.getDataState() == TelephonyManager.DATA_CONNECTED;
}

Categories

Resources