service implementation pattern - android

ok I have this application which needs to send periodic updates to a web-service, I have done a fair amount of research and I've come up with two service implementation patterns.
Implement a service with a thread, the periodic update time may vary therefore, I will put the thread to sleep with the required time-interval, then call the web-service again. I also need to update an activity, therefore will be using a broadcast receiver or a messenger.
Use a Service with a schedule timer/alarm manager, wake the system and use intent services coupled with a broadcast receiver.
Which would be the best approach?

I think I would go with the #2 option :
Create an IntentService to do the update.
Register a BroadcastReceiver with IntentFilter(s) and start the IntentService from it.
Use AlarmManager to Broadcast the registered action at the required time intervals.
I prefer this method because :
It is a very flexible pattern : You can start the service anytime by registering the same receiver for different actions like network connection changes, system boot changes etc.,
It keeps the logic loosely coupled from other parts of the app.
There is no hassle of managing threads. You get it for free by using IntentService
It is more android-ish way of solving this problem.

The main difference would be that a background service can be shut down by the user and then you won't get any more updates. If you register events with the AlarmManager, then you control when/if these events take place. If the user shuts down your app and goes into a task manager and shuts down any running services related to your app, the AlarmManager is still going to wake up and send a message that your BroadcastReceiver will receive.

Related

new to android - understanding the use of the service

I have been going through this very short tutorialand I am confused as to what is the function of the service. I am also confused as to what is the function of the broadcast receiver.
I tried to do some research and here is what i understand:
- services run in the background, but... i don't understand why we need something
to run in the background to make the phone wake up at a certain time.
I "think" the broadcast receiver acts as some kind of catcher's mit, in that
when the pending intent is launched at a specific time, it catches it then
launches the service... how close am I to the truth ?
As i think that services are used for long running tasks and especially in those cases that run when your main activity is not running.
For this functionality we can use threads this make us to say that a thread is created inside our activity and it can't be active outside of the our main activity,
that is the drawback that's why we have services .
Document URL
Services can be used to run long running tasks independent of your screen flow. For example, consider your application require to communicate with a server via socket throughout its running duration, you can start a service to handle this. Imagine that against starting the socket and making connection at the start of every activity, and clean up when that activity stops.
Services by default run in the main thread. But you can start separate threads in a service context, just like you do in an Activity. If your background task can overlap across multiple activities, then it is better to start it in a Service context because every Thread/AsyncTask created retains the context that it is running. In that case your Activity will be retained even if user navigates to another activity because a thread started from that Activity is already running. If Activity is retained, it might prevent all its views, images getting garbage collected.
What Services can't do is to directly alter UI components. For that it needs to communicate with the currently running Activity context. In short, if your non UI task does overlap the life time of a particular Activity, it is better to shift that task to a Service.
What is the function of the service ?
A service is a component which runs in the background without direct interaction with the user.
As the service has no user interface, it is not bound to the lifecycle of an activity.
Services are used for repetitive and potentially long running operations, i.e., Internet downloads, checking for new data, data processing, updating content providers and the like.
TO READ: Service
What is the function of the broadcast receiver ?
Broadcast receivers are the second kind of component. Like services, they only exist in the background and don't interact with you directly. But unlike services, they can't stay running or perform long tasks: they exist to respond to events. And unlike activities and services, more than one broadcast receiver can be started in one go.
Each broadcast receiver can react straight away, for example by creating a notification, or it can start a service or an activity to take further action. As soon as the broadcast receiver has handled the event, it is stopped and will not run again until another similar event is broadcast.
TO READ: BroadcastReceiver
I don't understand why we need something to run in the background to
make the phone wake up at a certain time ?
We don't want that the application should necessarily be in the foreground to wake the phone up.
Moreover we want notifications in the background.
We started the service. Now even if we close the application, you can get the phone wake up notification. This is so useful.
Services are great to interact with a user through notifications (a way of alerting a user about an event that he needs to be informed about or even take some action on getting that information). Many a time, applications will need to run processes for a long time without any intervention from the user, or very rare interventions. These background processes need to keep running even when the phone is being used for other activities / tasks.
To accommodate for such a requirement, android has introduced the "Service" component.
It runs in the background until it stops itself. This means that a service could be keeping your phone awake (using a wake lock), running down the battery, or using lots of network data, without anything showing on the screen.
I "think" the broadcast receiver acts as some kind of catcher's mit,
in that when the pending intent is launched at a specific time, it
catches it then launches the service... how close am I to the truth ?
Correct, they are meant to respond to an intent (usually one sent by a service or a system event), do something, and be done. When an intent is broadcast via sendBroadcast, it will be sent to all receivers that have matching intent filters.
Service - is a component of android, which runs in the background with out any UI. By default service will run in Main thread only.
Thread - is not android component, but still one can use thread to do some background task. Using thread in place of service is discouraged

android broadcasts and wake locks synchronization

I have a service A, which is started by WakefulBroadcastReciever from AlarmManager. Service A follows a standard pattern - performs a computation, then sends local broadcast to inform the system about the results, then calls WakefulBroadcastReceiver.completeWakefulIntent().
Depending of the results of the computation,i.e. content of the local broadcast, other local services may need to perform some computation immediately. However, am I guaranteed that the other services will receive the local broadcast at all before the device goes back to sleep?
If not, I guess another solution would be to use explicit callbacks.
Is there a standard pattern for this?
Thanks!
Local Broadcast manager has a sync mode. Beware ! The onReceive runs in the thread it is called from - not the main (UI) thread.

how to keep an Intent service running

I have two examples of Intentservice. One is the Download example in the commonsware book. the other is at http://www.vogella.com/articles/AndroidServices/article.html#servicecommunication_handler.
Both of these examples show the service executing a finite task and they both apparently destroy themselves by running to the end of the scope of the onHandleIntent event.
The service I am writing has to have events and listen for things. One is a LocationListener listening for GPS movement. Another makes Posts to a REST service and listens for replys. I want it to run until a time has elapsed or until it was told to quit by the activity that started it.
How do I keep it running? Where, for instance, do I put my implementation of LocationListener?
Thanks, Gary
How do I keep it running?
You don't. IntentService is designed to do a piece of work (or perhaps a few off a queue, if commands happen to come in rapidly), then shut down.
The service I am writing has to have events and listen for things.
Then you should not be using an IntentService. Use a regular Service, with your own background thread(s) as needed.
To keep a service running, your service need to return START_STICKY in the service method onStartCommand().
With this, the service will be running even if you exit form your activity.
Note:
The Android still kills services after some time (30 mintus to 1 hour) if they are not foreground services. Use startForeground(notification) to make it foreground.
good luck
You can achieve this in either of two ways,
AlarmManager
TimerTask
AlarmManager is android's in-buite class that allows you to execute certain action on particular time peroid.
TimerTask does same thing as AlarmManager, you can repeat certain action of your code again and again.
However AlarmManager is ligher in the execution so i suggest you to go with AlarmManager class.
Create an AlarmManager that fetches the GPS Co-ordinates and post them to server on regular interval basis.
Have a look at to this AlarmManager Example.

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/

BroadcastReceiver vs Service

Well, in android, what is the difference between doing something in broadcastReceiver and calling another service in broadcastReceiver? I think they both run in background,right?
Actually, what I what to do is:
In certain time of everyday, download the user event(eg: 9:00 am eat
breakfast) from database, and set up the AlarmManager to show
notification about the event.
Now I set up a alarm manager to do the above task. And I am puzzled should I directly accomplish this in BroadcastReceiver or call service in BroadcastReceiver to accomplish this.
Thank You.
You should do as LITTLE processing in a BroadcastReceiver as possible because (quoting from the Android Blog)
When handling a broadcast, the application is given a fixed set of
time (currently 10 seconds) in which to do its work. If it doesn't
complete in that time, the application is considered to be
misbehaving, and its process immediately tossed into the background
state to be killed for memory if needed.
You definitelly should call a service from the receiver for this purpose, if your action takes some longer time (connecting to the internet can take some). Broadcast receivers are limited by maximum amount of time, they have to finish.
Process Lifecycle
A process that is currently executing a BroadcastReceiver (that is,
currently running the code in its onReceive(Context, Intent) method)
is considered to be a foreground process and will be kept running by
the system except under cases of extreme memory pressure.
Once you return from onReceive(), the BroadcastReceiver is no longer
active, and its hosting process is only as important as any other
application components that are running in it. This is especially
important because if that process was only hosting the
BroadcastReceiver (a common case for applications that the user has
never or not recently interacted with), then upon returning from
onReceive() the system will consider its process to be empty and
aggressively kill it so that resources are available for other more
important processes.
This means that for longer-running operations you will often use a
Service in conjunction with a BroadcastReceiver to keep the containing
process active for the entire time of your operation.
from: BroadcastReceiver

Categories

Resources