15

Usually I start an activity with this code:

Intent i = new Intent(context, MyActivity.class);  
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);  

But how do I start the activity so that is left in the background?

digitalfootmark
  • 577
  • 1
  • 5
  • 19
  • if you need do something in background use Service instead of Activity – Selvin Apr 17 '13 at 10:10
  • 1
    As said in comments and answers, you cannot start an activity for it to stay in the background (you should use a **Service** for that). – Leeeeeeelo Apr 17 '13 at 10:15
  • 1
    I know Services are used for background processes. But the question was not 'should I use Activity for background processes'.. Instead just to test if I can speed up the initialization time of the Activity by starting it in advance. Looks like it is not possible, if it's an ordinary Activity. Thanks to everyone who have spent their time answering the question! – digitalfootmark Apr 17 '13 at 14:15

4 Answers4

8

You should use Services for this - in addition the Class Description.

M.Bennett
  • 1,019
  • 1
  • 10
  • 18
7

To keep an activity running in background , one can use services. Create a Background Service like :

import android.app.Service;
import android.content.Intent;
import android.os.Binder;

import android.os.IBinder;

public class BackgroundService extends Service {


    private final IBinder mBinder = new LocalBinder();

    public class LocalBinder extends Binder {
        BackgroundService getService() {
            return BackgroundService.this;
        }
    }


    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
}

Call the service in the oncreate() of your Main activity like this -

 startService(new Intent( MainActivity.this,BackgroundService.class));
Prax
  • 113
  • 9
  • you should also add `this.finish();` that will close the activity in the `onCreate()` of main activity. – Avinash R Aug 12 '13 at 14:25
2

U can do three thing

If u want to perform long running task in background with UI update. Use Asyntask. If u want to perform long running task in background only use intentservice. If u want some background task which is not too heavy a little work use services.

Nitin Gupta
  • 287
  • 2
  • 13
  • Services run in UI thread so if u r using heavy task on it app may hang.u can use services having some worker thread. – Nitin Gupta Apr 17 '13 at 10:21
  • With IntentService, once started, will it continue to run even if UI is been closed or not running? – BTR Naidu Dec 29 '15 at 08:37
0

Activity is usually meant to be shown to the user. If you do not need any UI you perhaps do not need to subclass Activity at all. Consider using i.e. Service or IntentService for your task. Or you can set Activity's theme to .NoDisplay.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141