Saturday, January 29, 2011

How to run in the background

So you are making an app that reads stuff in the background and posts to the screen. I did this for my battery graphing app. Another example would be an email program that tells you when you have new mail.

It's all fine except that the 'background' running doesn't happen a lot of the time (though sometimes it does, confusingly). Solution: recognize that Activities are supposed to run in the foreground and for your background tasks you need a Service.

Activities and Services are quite similar, the main differences being that Services don't have GUIs and don't get killed when the user hits the 'back' button or the system decides that it needs extra resources to render youtube videos of cats beating up iPads.

To start your service write this code in your activity, probably inside onCreate():

startService(new Intent(this, MyService.class)); // start doing stuff asynchronously (can be called multiple times)

Now create a class MyService:

public class MyService extends Service {

    public IBinder onBind(Intent arg0) {
        return null;
    public void onCreate() {
        // insert your code here
    public int onStartCommand(Intent intent, int flags, int startId) {
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;

Et voilĂ , your service will be started from your activity and will continue to run in the background until you kill it or the device shuts down, despite your activity opening and closing like Pacman's mouth.

No comments:

Post a Comment