In my application, I need to send the text message to the user after a certain interval. For that I need to run the message sending code in background. I am using the alarm manager to start activity at specific time.What to do? Is there another way to do this?
However, activity can't be run unless it's on foreground. In order to achieve what you want, in onPause(), you should start a service to continue the work in activity.
In order to make Android allow apps to run in background, all you need to do is press the open padlock icon right next to them. Once the open padlock changes and you get the “Locked” pop-up notification on your screen, you're all set!
You could look into using Services which are basicly UI-less Activities.
For those who want to do it with an Activity, and not by using a service (there can be situations when this is necessary), I did it by starting the Activity the usual way, and then in the Activity's onCreate I sent it to the background by calling moveTaskToBack(true) .
See Sending a running application to background programmatically
If you use this method, you should add an extra info to the intent by which you start the Activity, so that it knows in onCreate that it must send itself to the background. You do this by calling the Intent's putExtra method. In the Activity's onCreate, you get the calling Intent with getIntent, then retrieve the info you put there with getStringExtra, for instance (I used a string extra info). See the documentation for the Intent class.
Update august 2018: Note, however, that on some devices this can make your Activity blink (that is, briefly appear) on the screen before it's sent to the background. It appears that the system treats the notification to send the task to the background way too late. If you call the method in onCreate, it should have plenty of time to know about it before it draws the Activity window. IMO this is a system flaw, it shouldn't happen like this but it does.
So, anyway, if this is a concern and if you can, you'd probably better do it with a service.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With