How to run activity in background in Android

76,039

Solution 1

You could look into using Services which are basicly UI-less Activities.

Solution 2

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.

Share:
76,039
picaso
Author by

picaso

Updated on August 28, 2020

Comments

  • picaso
    picaso over 3 years

    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?

  • picaso
    picaso over 12 years
    please provide proper tutorial for using services in android.
  • Prasad
    Prasad over 9 years
    in services beacon monitoring is not working so please can we run activity in background
  • rightaway717
    rightaway717 about 8 years
    @kaspermoerch, could you please answer if it is possible to run Activity (not Service) in background for whatever tasks I need to do? I desperately, desperately need an activity.
  • Sharpe
    Sharpe over 7 years
    service is ho help if you want to request permissions.. (