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.
Related
Is it possible to start an app in the background? For example, if a push notification is received, then the app is started in the background,without invoking the UI/screen?
Because at the moment i have to invoke the app to the foreground and then put it back to the background which causes flickers.
You can use Android Services, they can operate in background and have their own lifecycle which can be managed. If you want to process in worker thread, use Intent Service. Developer Docs which I have given link of provide sufficient information about implementation.
Is it possible to start an app in the background
Not really, but there is no obligation to show any UI once your app is started so that'd would look like you started in background. In fact it'd be perfectly safe to have all the setup done without any UI. Calling setContentView() in your Activity's onCreate() is not mandatory as is concluding your onCreate() with ordinary finish(). That way you can i.e. start Service w/o showing any UI. There's even theme you can use with activity you do not want to display:
android:theme = "#android:style/Theme.NoDisplay"
For example, if a push notification is received, then the app is started in the background,
This is different story. Stop using Firebase's "automated" handling and process all pushes yourself. See How to handle notification when app in background in Firebase
First sorry for my english.
I have a problem, and i can't find a solution, it sounds like:
i'm developping an app that's getting my location from gps and send it to a tcp server on pc , and store the data into a listview (for example). I have set a timer that send the location every 2 seconds. Everything works fine even if i connect two clients to server, until the phones gets locked .. then my server receive ugly string ..it seems like the sent-strings it straddles (the string contains parts of data from bought clients, parts are concatenated) .. but when i unlock the phones the server receive normal strings again..
I want to know how to make my app run in the same parameters when lock screen occurs .. Any ideas?
If you are doing this inside an activity or a fragment you are probably having an issue with the lifecycle of your app. If you want to understand the lifecycle, read this documentation article: http://developer.android.com/training/basics/activity-lifecycle/index.html
Doing nothing on your onPause method won't prevent your activity from sleeping, Android can kill your activity anytime.
The proper way to do this would be inside a Service, a service is a special component on Android that is executed independently of what the user is doing or not doing, and in this case, you could create a service that holds a wake lock in order to prevent it from sleeping for the couple of seconds you need to send your data.
An easier solution would be to use something like this Location polling library and suit it to your needs.
When the screen locks your activity is either paused on stopped and it is important you handle these methods so that any interuptions are handled elegantly and without error. Or so the app will continue to run in the background.
If you read up about the activity lifecycle.
During normal app use, the foreground activity is sometimes obstructed by other visual components that cause the activity to pause. For example, when a semi-transparent activity opens (such as one in the style of a dialog), the previous activity pauses. As long as the activity is still partially visible but currently not the activity in focus, it remains paused.
However, once the activity is fully-obstructed and not visible, it stops (which is discussed in the next lesson).
Activity Lifecycle from android.com
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
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.
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.