Keep Service in sync with Application - android

I am wondering what is the best way to keep a service running while the application is running (may be in background) and then the service stopping when the application has ended (the application in this case has completely stopped, not in the background).
Another sub-question is: How to stop a service when application stops?
I realize one solution is to use BoundServices but is this the best way or good enough?
For example if an activity binds a service and then the system kills the activity and brings
it alive again then how will the service behave? Or are there other issues I am not aware of?
What would be the best way to implement this? Thanks.

Check out http://developer.android.com/guide/components/bound-services.html.
A bound service is the server in a client-server interface. A bound service allows components (such as activities) to bind to the service, send requests, receive responses, and even perform interprocess communication (IPC). A bound service typically lives only while it serves another application component and does not run in the background indefinitely.
You have two options to start the service:
1. bindService() to activity
2. startForeground() and bind while it runs
Option 1 will only run as long as the activity is in view and the runnable active. (example use would be to use service to download a file)
Option 2 will run as long as the application is running (even when the activity is in the background) This option requires that your service be listed in the notification bar.
You can have a service stop itself by calling stopSelf(int) (I dont think this works if a activity is currently bound) or you can call stopService() from an activity.
As for the system killing the activity question.... Without knowing what your service will be handling its hard to give advice on how to handle this situation. For the most part a service running in the foreground will be the last resource the system will try to reclaim. If the system kills the activity the services onDestory method will be called where you should do some clean up so that the next time it starts you can continue in a safe manor.
http://developer.android.com/images/service_lifecycle.png

Related

How to make service running even after manually swiping off of recent apps?

I am trying to build a count down timer that runs in the background in a separate thread. I am using a foreground service and passing a handler to the background thread from this service. So essentially, the activity will communicate with the service and the service will communicate with the thread.
Essentially, when the user swipes the app off from the recent apps, i need the timer to keep running.
What is the best design that does this?
You will need to use a started Service and startForeground().
Check this question for details.
Also if you create service in a separate process it will solve your issue.
Here is a great tutorial
A started service can use the startForeground(int, Notification) API
to put the service in a foreground state, where the system considers
it to be something the user is actively aware of and thus not a
candidate for killing when low on memory.
Like Ivan previously said, it is a combination of startService(), binding calls and startForeground() call to keep the service running in the background. Don't really require a separate process to do this.

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 - Can an activity and a service communicate using the Observer design pattern or similar?

Is it possible to make an activity and a service communicate, using the Observer design pattern?
I want to make them communicate both ways by giving them both the role as Observer and Notifier
The reason why I want to do this, is that I want low coupling between them. So if the activity crashes for some reason, the service will still be running and still trying to notify the GUI without crashing.
The reason I want the service to remain running, is that it acts like a server in a LAN and I still want the system and the clients to communicate even when the GUI of the server is gone.
If this can't be achieved using the Observer pattern or is too complex, is there another way to achieve what I described above?
Thanks in advance
You can run the service as foreground if your are using notification . so when the activity exit the service can update with the notification or remote views.
Also , When you start the activity you can bind the service from the activity to communicate using service connection.
bindService(new Intent(this,
YourService.class), mConnection, Context.BIND_AUTO_CREATE);
A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)
check the link - http://developer.android.com/reference/android/app/Service.html
http://developer.android.com/guide/components/bound-services.html
You could have a communication from Activity to Service with a usual Binder. The Service can inform the Activity about changes with a Callback, which you can register in onServiceConnected() and unregister in the Activities onPause().
With this you have a two way communication between Service and Activity and the implementation isn't to complex.
So if the activity crashes for some reason, the service will still be running
The thing is, Activity doesn't crash. The whole app process does. So if you want to separate Activity and a Service, you need to run them in defferent processes. Note sure about if Service is restarted after process crash, though.
Take a look here https://stackoverflow.com/a/12022185/468311, that would be a good start for you.
If this can't be achieved using the Observer pattern or is too complex
As suggested, use Binder. Or you can communicate using Intents.
But keep in mind that Service wasn't intended to be used as a forever-running piece of your app. Try avoding this. Use Service for pereodic background operations.

Long running Android 'service'

I have an Android app, in which Activities fire long running operations that run in the background. These operations interact with the Activities when done. I'm developing a component that handles the Activity/Long-Running-Task coupling, taking care of activities being destroyed and recreated.
Right now that component is implemented as an Android service. The activities call bindService and use the resulting IBinder to start and track tasks. I decided against using startService, because I prefer the richer API possible through a Java interface.
Now the problem. Activity A start ups, binds to the service and calls serviceApi.runTask(...). Activity A is then destroyed (because the user flips the phone, for instance) and recreated as Activity A'. A' then binds again to the service, announces its existence and everything should be running nicely.
Except that my Service gets destroyed. When Activity A is destroyed, it unbinds from the service. Android sees there are no more clients, and kills the service. When Activity A' is created, the service is created again, and I lose everything the old service had.
The only solution I can see is using a singleton for the service. And then it doesn't really have to be an Android service, just an instance that's accessible to everyone. Is that frowned upon in Android? Is there a better design that fits this problem?
Editted: Even if I call startService and then bind to it, nothing guarantees that the service instance will exist as long as the application is running. Android can kill sticky services if resources are low. Killing the service will cause the application to malfunction, and I can't have that.
Even if I call startService and then bind to it, nothing guarantees that the service instance will exist as long as the application is running.
Correct.
Android can kill sticky services if resources are low.
Also correct. All "sticky" means is that Android might restart the service.
Killing the service will cause the application to malfunction, and I can't have that.
It is impossible to create a service that is guaranteed to run forever. For starters, users can get rid of your service whenever they want, because users detest developers who have pointless services that run forever. Writing everlasting services is necessary only in very few cases; otherwise, it's just sloppy programming.
The only solution I can see is using a singleton for the service. And then it doesn't really have to be an Android service, just an instance that's accessible to everyone. Is that frowned upon in Android?
Singletons (a.k.a., static data members) will go away when the process is terminated. The process will be terminated eventually, particularly if there are no active services and none of your activities is in the foreground..
Call startService and in onStartCommand return START_STICKY. It should keep the service going.
You may also want to look into foreground services:
http://developer.android.com/reference/android/app/Service.html#startForeground(int, android.app.Notification)
Yo have to create persistent service. Refer to this manual.
In a few words - don't call bindService, call startService.

Android: Creating a service that survives the application that started it

I'm developing an Android application that consists of:
a lightweight background service that logs events to a DB
a heavier GUI application that summarizes these events and displays graphs.
I'm having trouble creating the service part, though. The graphic application can use quite some RAM, and when it goes to the background, the OS closes it after some time of not being used.
The problem is, when the application gets shut down, so does the service. This is bad because this keeps me from recording further events. I don't care if the application gets terminated, but the service needs to keep on running.
I have tried numerous ways to keep the service alive, like having it use threads or a differently named process than the main app. Nothing has worked, and I have found no help on any of the android developer pages or forums.
Thank you for your advice!
Try to return START_STICKY in your service's onStartCommand(). Also how do you start your service? If you use bindService() with BIND_AUTO_CREATE flag it will be stopped automatically on unbindService(). You should explicitly start it with startService() and stop calling stopSelf(). Than OS keep your process running on the background after activity will be closed. Note: the activity and the service run in one process and it's imposible: "application gets terminated, but the service needs to keep on running". But it is possible to keep the process running without activities, with service running on the background.
Read the detailed info http://developer.android.com/reference/android/app/Service.html.
good luck!
You should use the AlarmManager to respawn your service. You just can't keep your service alive eternally.
Check about the lifecycle : http://developer.android.com/guide/topics/fundamentals.html

Categories

Resources