In an Android app, I perform a data poll from server on push. When the device receives a push it pings the server to get the latest data.
As the user base grows, Server could potentially get 1000's of request at the time of push taking the backend down. I am looking for a good alternative so that I can spread out the server call in a given time window say next 2 hours. What is the a good way to do it?
I was looking into GCM Network Manager One-off task. One thing I am not certain is that even if I set a time-window start now with offset of 2 hours, since the device would be connected to the network when the push is received, it would trigger the server call right away defeating the purpose.
Any suggestions on what might be a good way to resolve this?
I don't think the task will execute immediately, as the GCM network manager doesn't execute only when the network is up, but tries to batch jobs together to reduce the number of wakeups and power consumption.
However, to be safe, when you create the OneoffTask, you can set an execution window. There you can set a minimum amount of time before the task will run. I suggest using a random number of seconds, e.g. between 0 and 60 to reduce the potential load on your server.
Related
I have an mobile application (iOS and Android) and I need send some notification from my server to these, then the mobile app need to make some tasks and when they finish, send a message from mobile to server to confirm. I have thought using Push Notification, but the problem is if the user disable this feature, the app will never receive this notification. Anyone know some direct communication server-app but keeping security?
You may try the long polling technique. But it will drain your battery very fast, so be careful. The main idea is that you set connectionTimeout to a very very long time (30 mins for example) and when not closing that connection until the server says there is something. After receiving an answer or timeout, just reopen it.
Another approach is to make some method like getJobStatus on the server, assign a unique id for your job and ask the server if it's complete every N minutes for example.
When trying to synchronise the client with the server, we usually need to combine both push and pull.
Something you can think of:
The server provides an API that allows the client to get the latest updates.
On the client side, when the app is active, use a timer to try fetching updates every N minutes.
When the app is in the background, use a background fetch to try fetching updates. In this case, the user doesn't care about if the task is done instantly, because his is not using it.
Call the getUpdates when the app becomes active from the background, to make sure handle the updates when the user starts to use it.
Requirement - I need to get the user's location coordinates every 15 minutes roughly and post it to the server. It is necessary to post data roughly at these intervals.
Implementation - I've made a sync adapter instead of using AlarmManager as it saves battery. I've set ContentResolver.addPeriodicSync() to sync my app every 15 minutes roughly which gets the current location and posts to server.
Problem - In case there's no internet connection, I want to continue taking the user's location every 15 minutes and save them in the local sqlite database. When the internet comes back again next time then I'll post all the saved locations in one go so that server data remains consistent and after that sync will resume as normal.
The main problem is that when there's no internet then the sync stops and I stop getting periodic sync callbacks in my app and I'm not able to save data in the local database. So what I want is that even when there's no internet I keep getting callbacks at regular intervals till the internet comes back and auto sync starts again. Can the sync adapter do that?
One solution I can think of is that I get a broadcast when the Internet stops and at that moment I start using the AlarmManager to start a service every 15 minutes and get the location and save to local database. And when the internet comes back on then I stop using the AlarmManager and go back to auto syncing.
Solution 2 - Provided by David Medenjak below. It is also efficient due to AlarmManager's setInexactRepeating() behavior which tries to imitate Sync adapter's behavior by scheduling Alarms for different apps together to reduce the number of times the CPU wakes up. Also it leads to a little simpler implementation. Would this the better way than the previous solution comparing the pros and cons?
Still any better way to achieve this?
You are mixing two things:
Getting the user location every 15 minutes
Syncing the data with the server
If you start mixing those you have a service and sync adapter that are both strongly dependent on each other, you have to check for states which of those has run and which should run. You might end up with the exact thing that you want (syncing every 15 minutes, just cache it if user is offline) but it will be hard to test and maintain.
Always use a service that is run every 15 minutes to store the current user location.
Periodically sync all updates to the server. This may also happen to be every 15 minutes, but you should not depend on this.
By having one part just storing the location and the other part just synchronizing the data you will have a much easier time handling things. And you also don't have to worry about internet connection or the interval of the synchronizations (since sync adapters are not guaranteed to run at exact times).
Concerning battery life (comments)
There should be no big difference whether a SyncAdapter uses gps and posts it immediately or a service persists it for the time being until the adapter syncs it. As soon as a task has to run every x minutes the device will have to wake up.
There might be slight improvements if the synchronization is run at a slower rate compared to the service, since the gps alone might not need any internet connection.
IntentService - runs every 15 min (using AlarmManager) and saves the user location in the db and mark it as unsent.
SyncAdapter - runs every 15 min and ties to send all unsent locations to the server. On success mark the location as sent. Android will make sure it's only run when there is a internet connection.
Edit:
The key point is separating the two sub-tasks (also suggested by #David Medenjak):
1) Get a location update and store it in a db
2) Send the location updates to the server when there is a network connection.
The FusedLocationProvider has a method
requestLocationUpdates (GoogleApiClient client, LocationRequest request, PendingIntent callbackIntent)
for when your app is in the background. Link
This method is suited for the background use cases, more specifically
for receiving location updates, even when the app has been killed by
the system.
You can use a LocationRequest to set the priority, interval, power consumption. Link
When you receive the pending intent, you can insert the location in the database and request a sync using the sync adapter.
I have an application with list of data that I get from server with http request. Now I want to make a notification when new data is available and I assume that it can be achieved with service.
Is that a good practice? Is there any limitations for number of requests made from service?
What I want to achieve is something like gmail application. When I get a new email, notification is shown.
I want my app to be as up to date with data as possible, but I understand that making requests every 5 seconds might be too much.
I am open to all alternatives and various ideas how to do that.
Not sure if you really need to pull data every 5 seconds. Of course, it is too much. You have two options:
Use GCM as #duynt suggested in comment. Follow Try cloud messaging for Android if you've never used it. This way you don't need to worry managing your service locally but whenever there is a latest data available, you will get notification so you can place request to get that and update in notification.
GCM needs An application server that you must implement in your environment. This application server sends data to a client app via the chosen GCM connection server, using the appropriate XMPP or HTTP protocol. Take a quick look About GCM connection server.
For any reason if you would like to pull data from your local Android Service component, you can still do that. But 5 seconds frequency is really high. As majority of the times the device is in sleep mode, you have to wake up the device then send request to pull data. Waking up device every 5 seconds means a battery drain along with consuming data.
If you still want to proceed with local service option by increasing the frequency, make sure you follow How to use http in sleep mode and implement it that way otherwise it wont work in deep sleep mode.
You have to make a decision now.
For one of the screens in my android application, I need to listen to server indeterminately - ie; I have few fields in the screen whose values change continuously so long the screen is kept open. The values to be updated will be provided by the server continuously. I understand that normal http connection would not be a solution here. Also, I do not wish to make continuous http requests owing to performance reasons. What is the best way out in order to accomplish this.Is GCM Cloud Connection Server a good solution for my requirement. Or are there better solutions? Please advise.
Any help is much appreciated.
I think there are a two options. If you don't own the server yourself I would start a service to run in the background and bind to it. The service would poll the server at some time interval depending upon how often you want the values to update. The activity would then receive periodic updates and update the views. Given that the information that you're updating is really not all that large, updates every 30s to a minute wouldn't take a toll on performance at all since all of the work would be done in an asynchronous task.
Using an AlarmManager to accomplish this.
If you own the server then you could implement the GCM model, and only send updates when data changes. This is assuming that every user of the app would get the same set of updates of course.
Introduction to GCM
Keeping screen on could be battery consuming. If you own the server the changes can be pushed to the app using the GCM service.
As far as I understand, GCM bundles push messages from several server trying to push the messages together and hence is an optimised way to communicate.
Alternatively, you can bring up a server which can keep polling the original server and push the changes to the app through GCM.
Recently google introduced push-to-device service, but it's only available 2.2 and up.
I need a similar system in my app, and I'm trying to get around limitations.
The issue is battery life. Since the user must be notified immediately about the changes on the server, I thought to implement a service that would live in the background (standard Android service) and query the server for updates.
Of course, querying the server, even each second, will cost a lot of bandwidth, as well as battery, so my question is this: does it make a difference if the server is holding the response for some period of time? (the idea behind Comet type ajax request)
Works like this:
Device sends request for data update
Server gets the request and goes in the loop for one minute, checking if there are updates on each iteration
If there are updates, server sends response back with updates
If not, service goes on to the next iteration.
After a minute, it finally sends the response that no data is yet available
After response (no matter whether empty or with data) Android fires another such request.
It will definitely cost less bandwidth, but will it consume less (or even more) battery?
Holding a TCP socket (and consequently waiting for an HTTP response) as you suggest is probably going to be your best option. What you've described is actually already implemented via HTTP continuation requests. Have a look at the Bayeux protocol for HTTP push notifications. Also, check out the Android implementation here. For what it's worth, that's definitely what I would use. I haven't done any sort of analysis of it, but this allows you to minimize the amount of data transmitted over the line (which is directly proportional to the power consumption) by allowing the connection to hang for as long as possible.
In short, the way Bayeux works is very similar to what you've suggested. The client opens a request and the server waits on it. If it has something to send, it sends it otherwise it simply waits. Eventually, the request will timeout. At that point, the client makes another request. What you attain is near instantaneous push to the client from the server without constant polling and duplication of information like HTTP headers, etc.
When the phone is actively using the networks, it's battery is used more. That is to say when it sends the request and when it receives the response. It will also be using battery just by listening for a response. However, will the phone download data, checking to see if there's a response? Or will the phone just be open to receiving it and the server will push the response out to the phone? That is mainly what it depends on. If the phone is just open to receiving the response but does not actually use the network while trying to download some response the whole time it's waiting, it should use less battery.
Additionally, the phone sending a query every minute instead of every second definitely uses less battery, as far as using the networks goes. However it depends on how you make the phone hold, if you tie it up with very complex logic to make it wait it may not help battery life. That's probably not the case, however, and I would say that in all likelihood this would work out for you.
In closing, it should help the battery but there are ways you could make it in which it would not. It wouldn't hurt to write the program and then just change some type of variable (for example WAIT_TIME to 1 second instead of 1 minute) and test battery usage though, would it?