im currently developing an app which plays the steam audio using MediaPlayer class. And i'd declare its main (Player) activity as SingleTop. Also on button "Back" it does moveTaskToBack(true) which acts the same as button Home does. So it just stays and plays on background and if user wants to see the gui he just starts the app once again (which is less convenient) or he clicks the special app's notify. Exit provided via menu.
but what are the benefits of using service instead of activity in such case? Definitely it would be more complex to develop, i have to say. Even instantiating the GUI while "on background" will take much more time, i'm afraid.
From the Android Documentation:
Activities
An activity represents a single screen with a user interface. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails.
Services
A service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provide a user interface. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity. Another component, such as an activity, can start the service and let it run or bind to it in order to interact with it.
also
Once started, a service can run in the background indefinitely, even if the component that started it is destroyed.
The Android OS can destroy your Activity if it runs out of resources, but it won't destroy the service.
EDIT: you should use startForeground() to ensure your Service won't be killed in situations where the resources are low. From the docs:
Make this service run in the foreground, supplying the ongoing notification to be shown to the user while in this state. By default services are background, meaning that if the system needs to kill them to reclaim more memory (such as to display a large page in a web browser), they can be killed without too much harm. You can set this flag if killing your service would be disruptive to the user, such as if your service is performing background music playback, so the user would notice if their music stopped playing.
Related
In my app I have two activities, A and B. A downloads some data and starts activity B when the data is downloaded - this is done through a BroadcastReceiver whose onReceive() method starts B through an intent.
My problem is that, when I my app goes to background while the data is still downloading (e.g. I start my app, then quickly click the "home" button, or switch app with the square "switch" button), my app comes back to foreground once the data is downloaded... annoying.
So far I've tried adding flags and setting actions on the intent to avoid that, including intent.setAction(Intent.ACTION_SCREEN_ON), which might be close to the answer: it works nicely on a device running API 16 but not on mine which is running API 22.
Typically, one uses a service to carry out operations in the background. Services don't have a UI (for obvious reasons). By definition, an Activity is a foreground task - the behavior you're seeing is exactly what is supposed to happen.
I'd strongly suggest NOT trying to turn an activity into a service. You'd be working against the whole application life cycle when you could use a feature in Android designed for the very purpose you seek.
Here's a quick resource, I suggest you read more on services:
https://developer.android.com/training/best-background.html
The BroadcastReceiver for an Activity receives and processes Intent objects even when your app is in the background, but doesn't force your app to the foreground. If you want to notify the user about an event that happened in the background while your app was not visible, use a Notification. Never start an Activity in response to an incoming broadcast Intent.
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
With respect to Process lifecycle, Android system tries to maintain an application process for as long as possible, but eventually needs to remove old processes to reclaim memory for new or more important processes. To determine which processes to keep and which to kill, the system places each process into an "importance hierarchy" based on the components running in the process and the state of those components. Processes with the lowest importance are eliminated first, then those with the next lowest importance, and so on, as necessary to recover system resources.
One of the classification is :
Foreground Process : A process that is required for what the user is currently doing. A process is considered to be in the foreground if any of the following conditions are true:
1. It hosts an Activity that the user is interacting with.(the Activity's onResume() method has been called).
2. It hosts a Service that's bound to the activity that the user is interacting with.
3. It hosts a Service that's running "in the foreground" —the service has called startForeground().
4. It hosts a Service that's executing one of its lifecycle callbacks (onCreate(), onStart(), or onDestroy()).
5. It hosts a BroadcastReceiver that's executing its onReceive() method.
What can be real life examples of scenarios given above I am asking this because it will help me and others as well in differentiating between this situations.
1)THe app that is currently on top of the stack (the one the user is using)
2)An app with an Activity that has called bindService on any service. The idea is that if it killed that service, it might lose data. An example of this would be a facebook app, which has a background service to fetch data every so often. If the user has it open, it would qualify
3)This is a service that has declared that its feeds data to a UI. An example of this would be a facebook app where the user didn't have an activity with it open
4)This is a service that's just starting or just finishing. This would be pure luck to have happen, but its basically saying it will try to let it start up or finish cleanly before killing it
5)This is any app that's currently responding to an event. An example would be an SMS app that was just notified of an incoming SMS and needs to deal with it. It will be allowed to run until its done, because doing otherwise may lose data.
How do I keep a service running, when all activities of an application are viewable. and close the service only when I leave the app?
Is there a way to start a service in one activity of an app and stop that same service in another activity of that same application?
I don`t want that service to continue running when the user leaves the application.
There is really no concept of 'application' and leaving it. What happens if open a link from one of your activities, launch the browser to view it, then come back via the back button? Did you really leave the app?
What does your service do? Do activities bind to it? If so, it will be automatically shut down after the last client unbinds. If not, it should shut itself when it has finished doing it's work (Cf. IntentService). If it doesn't fit either of those patterns, maybe you don't need a service at all, just some background thread(s)?
Edit (based on comments below):
For a service running a media player, the usual way is to have an ongoing notification for the service that lets the user bring up an activity to control the service. Or have buttons on the notification in JB to achieve something similar. Additionally, if you make the service a foreground one, that will give it higher priority and it is less likely to be killed if resources are low.
I have created an application in Android. This application should never die (even when sent to the background).
Currently, after a while the Service manager returns "No longer want..." and terminates it.
I've read that one solution whould be to create a service. However my application is way to complicated to be splitted into two functionality sets (one for the service and one for the application).
Is there any "trick" in order to keep my application running at all time?
Could I create a dummy service inside my application that might force the android to keep my application alive?
Is there any other way?
FYI: 1) It's a customized application that will not be released on the Market. 2) Handsets can't be rootted.
Thanks
You must create a Service to have a persistently running app, even after all your Activities have been sent to the background due to user pressing the Back button, answering a call, switching to another app, etc. You should review the Android Process Lifecycle which states that:
Sometimes an Activity may need to do a long-running operation that
exists independently of the activity lifecycle itself. An example may
be a camera application that allows you to upload a picture to a web
site. The upload may take a long time, and the application should
allow the user to leave the application will it is executing. To
accomplish this, your Activity should start a Service in which the
upload takes place. This allows the system to properly prioritize your
process (considering it to be more important than other non-visible
applications) for the duration of the upload, independent of whether
the original activity is paused, stopped, or finished.