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.
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");
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();
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.
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.
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With