An Android service method called on a different thread. Is it still running on the main thread?

If I understand correctly, Android Service

s are launched on the main UI thread by default. So for any work outside the main thread, I found people suggesting starting a separate thread in Service

.

However, my question is that the method Service

is being called on a different thread, i.e. AsyncTask

or new Thread(...).start();

, does the method execute Service

on the calling thread? or is it running on the main thread that is supposedly running Service

?

In other words,

new Thread(new Runnable() {

    @Overrde
    public void run() {
        myAndroidService.doSomething();
    }
}).start();

      

will be MyAndroidService#doSomething()

called in this new one Thread

?

+3


source to share


2 answers


The method always runs on the thread that calls it.



The method doesn't really belong to any thread, so yes, although the method is defined in your service, it will execute on the thread AsyncTask

, not the main thread that your service is running on.

+6


source


Yes, as Martin said above.

Alternatively, you can check the method flow information:



private void doSomething(){
    Log.i(TAG, "I'm doing something in thread " + Thread.currentThread().toString());
}

      

+1


source







All Articles