android 4.0 pattern for download/sync data - android

I have an application for android 4.0(android:minSdkVersion="14") with lots of SQLite tables that needs to download(not delete or send) new data from my server. At the moment the user has a sync button, however i would like to implement something that would synchronize automatically when 3G/Wifi is on and every 1-2 hour.
What pattern or best practice should i use? an Alarm thing, or a local service, or a remote service, or something else?

You need two things:
An alarm (Have a look at tutorials about the AlarmManager) to run your code every 1-2 hours
A broadcast receiver to intercept network events. (see for instance BroadcastReceiver when wifi or 3g network state changed)
Make sure your code runs in his own thread, you don't want to execute anything heavy in the broadcast receivers. A good place to run such a code would be a service with his own separate Thread.

Use a service and a broadcast receiver (for the wifi state, as mentioned above). Remember that polling a web-server every X times is a really bad experience in terms of battery usage. Try building a GCM web service.

I would recommend you read Chapter 19 of Android Pro 4( http://my.safaribooksonline.com/book/programming/android/9781430239307/chapter-19-broadcast-receivers-and-long-running-services/navpoint-164 ) and then use the already ready source code from here http://www.androidbook.com/akc/filestorage/satya/documentfiles/3810/ProAndroid4_Ch19_TestReceivers.zip
I did this by using Alarm + ALongRunningReceiver(=Broadcast Receiver) + ALongRunningNonStickyBroadcastService(Local Service) + LightedGreenRoom(Handles CPU partial_wake so it doesn't fall asleep).

Related

Monitoring IntentService with AlarmManager or Service with Thread

I'm building a monitoring app that will capture as much info as possible from the mobile device, like running processes / active connections / networking statistics / active interfaces etc. Obviously I will need a service that will be running in the background for that, but I'm not entirely sure how to implement it.
Someone suggested that I create an IntentService that will execute at specific intervals using AlarmManager, do its thing and then die again.
In this thread people suggest an implementation using an always-on Service that starts its own thread to do the work, put it to sleep and then again. One also suggested that AlarmManager is used too to make sure that the service will be restarted if the OS kills it.
What's the mpst appropriate implementation for monitoring real time data? (or the up/downsides of each). Note that many of the info I'm capturing do not produce intents (so I can't just register receivers)
Thanks a lot:)
Note that many of the info I'm capturing do not produce intents (so I can't just register receivers)
Then you won't be able to use an IntentService, since your app won't know when to fire it up.
If you want "real time" updating of info, then you will have to use a Service (with or without it's own background thread). You cannot use an AlarmManager because it will almost always run too late (not "real time").
Do note that it takes some effort to have your service run always as there are a couple of different scenarios where it can stop running, and even when you have done all you can to achieve it, there are still ways for OS or user to stop it from running.

Proper way to periodically poll location on Android?

I'm looking to build something similar to Google's field trip application. The key attributes that I'm looking to prove out are:
A background "job" that runs every X minutes and checks the user's location and make a webservice call(this question doesn't really concern the location part)
The job should run even if the user exits the main application.
The background job should automatically start up after the device reboots.
After a reboot the application should not show up on the "recent/history" screen
My reading has brought me to a number of different classes/APIs from broadcast reciever of on boot, to regular services, to alarm manager, etc. It seems there are multiple ways this could be made to work, I'm curious what the community recommends as a high level approach?
You would definitely want to use a broadcast manager to get the boot event.
As far as polling for location goes, it sounds like you would want to use a Service and start it once you received the boot event.
Services
You could then use an event bus like Otto to communicate your events to wherever you need.
As far as the timing goes you could use a job manager to run things at various intervals, or just simply create a runnable and have it run as often as you like. As long as you keep it in the service, you should be able to control the length that it will run just fine. Regardless of whether or not the app is closed.
I think you may divide your solution into two parts :
Starting the app or the service after the device re-boot process completed by defining a Broadcast receiver that has the following action :
And on the "onReceive" method of the broadcast "do your task " start the service that listen to the location service updates.
For the part of listening to the location updated every x minutes, you would better use the alarm manager to "wake up" the service every x minutes, and every service sets the alarm for the next call.

Good Practices for running Android App in the Background

I have a VOIP app that I would like to always run in the background to make it responsive to incoming calls. Reading through some forums I found running the app in the background would cause a battery drain.
Are there good practices that I should follow so as to run the app in the background?
Reading through some forums I found running the app in the background would cause a battery drain.
It is more that having something run all the time increases your opportunity to drain the battery.
Are there good practices that I should follow so as to run the app in the background?
Being a VOIP app already violates some of the "good practices". For example, you will need to (try to) have a service that runs forever, to maintain your open socket connection to the VOIP server. And, depending upon how your networking is set up, you might need to try maintaining a WifiLock, which will drain the battery.
Generally speaking, then, you just want to make sure that your service is doing as little as possible except when a call is in progress. For example, while you may need to send packets over to the VOIP server periodically to keep your connection alive, try to do that as infrequently as you can.
There are many smart VoIP applications that use Push Notification feature. That will not eat up as much battery, but you must have a consistent internet connection. One such option is Axvoice. Check out their apps at: http://www.axvoice.com/support/mobile-voip-applications.html
They will also run in the background like other apps, but the difference between Axvoice and other apps is you can reduce battery consumption because it will not be communicating with live servers all the time. Please have a look at this: http://www.wikihow.com/Save-Battery-Power-on-an-Android
Use a Broadcast Reciever. It is documented here
http://developer.android.com/reference/android/content/BroadcastReceiver.html
A BroadcastReciever will execute it's code when the specified broadcast is broadcasted through the system. In other words when you receive a call the system sends out a broadcast saying that there is an incoming call. If your receiver is made to pick up on that broadcast than it will react. Think of it like the Android system is broadcasting a lot of different radio stations and a BroadcastReciever is like a radio. You can set it to pick up whatever broadcast you want and execute some code when it does.

IntentService, Service, or AsyncTask

What would be the best way to implement this. I have an Android app that will use my python server to allow communication between 2 phones in rounds. Rounds mean that they can't talk to each other until a round start and once they send a message they can't send another until the other person responds which will then start a new round.
I was thinking I would use the IntentService but it seems wrong to have the server constantly starting and stopping and I don't won't to have to worry about the issues with asynctask or is that the best way to handle it. How could I have a service that should receive and send messages to the client, seems services are more one way things?
Intent services are nothing more that worker threads that are triggered by intents, execute their actions in a separate thread and then get shut down. They are designed to be started and stopped.
If you need to perform stuff like an http get, or in any case interaction that do not require to stay connected to the server, use intent services and get your activities notified using broadcast events.
If your app needs to stay connected with the server (i.e. permanent tcp connection), the way I'd go for is to have a service (not an intent one) that performs the networking stuff using an asynctask or a more classic thread hosted in the service. You can then make the activity interact with the service using bindToService() .
I'd recommend not to use asynctasks inside an activity. You will risk to loose the server response in case of horizontal / vertical view changes, as oneilse14 stated in his reply.
I highly recommend the IntentService/Broadcast Receiver route. Avoiding the nasty configuration change issues associated with AsyncTask will make your life ten times easier.
As far as i understood your problem is of type worker-queue model Producer-consumer model). Intentservices are meant to do that. You should use services if and only you need to do multithreading. You do can communicate with Activity and Service by using IBinder interface.
Asynctask are just a specialized threads so that you can update your UI easily. But for your case IntentService seems to be best option.
I would use an Alarm, which is scheduled via the AlarmManager, as then it can be set to check if the round has started/turn. It has the advantages of a service but not the horrors of battery drain. It takes a frequency to how often the Alarm should run, which even includes enumerations of time (e.g. 1 hour/day/week).
When the Alarm runs it could poll to see what the current state is and react accordingly. For example a notification could go into the status bar and phone could make an audible noise and vibrate.The benefit of this is that the user does not have to keep the app running as the Alarm will trigger a broadcast receiver.
An example of the Alarm code: http://www.androidcompetencycenter.com/2009/02/android-basics-alarm-service/

Best way to have an Android app poll periodically in the background

Take the Gmail app as an example. Whether the phone is on or not, it polls every 10 minutes or so to download new emails which may have arrived since you last checked.
I know how to create a new service and bind to it. But I can see a few ways to accomplish this:
Bind once, and have the service run in an infinite loop, sleeping for 10 minutes between each loop
Bind and unbind right when it's done, scheduling the next bind somehow in 10 minutes
Using the AlarmManager class to schedule future polls
What are the trade offs? How does the Gmail app accomplish it?
Thanks!
Gmail app uses pushing, not polling. I suggest using this technique instead, polling is a battery killer in mobile devices.
To implement pushing, take a look at C2DM.
If you still want to poll, the recommended way would be to set up a periodic alarm in the AlarmManager.
UPDATE: Google has deprecated C2DM and replaced it with Google Cloud Messaging (GCM)
UPDATE: Google has deprecated GCM and replaced it with
Firebase Cloud Messaging (FCM)
For a continuous, but not intensive poll like the one you comment (in the range of minutes between polls), I would implement it with AlarmManager. That way you make sure the phone wakes up to poll without the need for a wakelock, which would destroy your battery. As CommonsWare pointed out, you will still need to implement a wakelock for the time your code is executing, but you can release it as soon as the code is done, avoiding keeping the phone on while just waiting. See his comment for an example on how to implement it.
I would use a Service if, instead, you need faster polls during a shorter period of time (seconds between each poll), since setting alarms does not make sense to such short periods, and the battery would drain anyway.

Categories

Resources