2

I made a Service that uses a Thread when it is started. I want to keep the service running when my application is closed (START_STICKY).

To make the service keep running, I have to return START_STICKY:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
     new Thread( new Runnable() {
        @Override
        public void run() {
            while(true) {
              try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
    return START_STICKY;
}

How can I return it with my thread?

Onik
  • 19,396
  • 14
  • 68
  • 91
tomss
  • 361
  • 3
  • 13

1 Answers1

0

It seems to be a misunderstanding of the concept of Thread. The thread you've started in onStartCommand() does not "prevent" the method from returning. What happens here is as follows:

  1. onStartCommand() is called on some thread (likely the main one)
  2. Thread.start() returns immediately followed by returning from onStartCommand() with START_STICKY flag.

As a result there are at least two threads running, the one on which onStartCommand() has been invoked, the other one that performs the run() method.

Onik
  • 19,396
  • 14
  • 68
  • 91