Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting a Service in a separate thread

In the Android docs, it says that a Service runs in the main thread.

What happens if I start my service in a separate thread? Does it still run on the main thread?

I am not talking about using android:process in the manifest file, but rather something like:

Thread thread = new Thread(new Runnable() {
    public void run() {
        // Start service
    }
}).start();

Don't worry, I will not do it like that, I am just curious.

like image 600
kenny Avatar asked Dec 31 '13 16:12

kenny


People also ask

How do I start a thread in Java?

Another option that has been in .NET since the beginning is the Thread class. You can create a new Thread object, set up various properties such as the method to execute, thread name, and priority, and then start the thread. var t = new Thread(BackgroundTask); t.Name = "My Thread"; t.Priority = ThreadPriority.AboveNormal; t.Start("Thread");

How to create and start a new thread from an activity?

To create and start a new thread, from inside an activity, you can say: Thread t = new Thread(){ public void run(){ getApplicationContext().bindService( new Intent(getApplicationContext(), MyAndroidUpnpServiceImpl.class), serviceConnection, Context.BIND_AUTO_CREATE ); } }; t.start();

Why can't I thread a service?

Any solution which uses Threads, Runnables, AsyncTask or otherwise with a Service will have a common problem. The Service will block the calling Activity until after the service is started. And thus doesn't effectively thread the Service in certain cases. The solution to this is to use the IntentServicesubclass.

What is threading in operating system?

System. Threading Thread. Start Method System. Threading Causes a thread to be scheduled for execution. Causes the operating system to change the state of the current instance to Running.


1 Answers

startService() starts a service in the main thread (the same as starting an Activity or any other component). In doesn't matter what thread you call startService() from.

Source: http://developer.android.com/reference/android/app/Service.html

"When a Service component is actually created, for either of these reasons, all that the system actually does is instantiate the component and call its onCreate() and any other appropriate callbacks on the main thread."

like image 97
Steve M Avatar answered Oct 06 '22 07:10

Steve M