Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start service in new thread in android

Tags:

android

I'm new to this android. i'm using a service to do some background work. so i'm starting the service from my activity as following.

        getApplicationContext().bindService(         new Intent(getApplicationContext(), MyAndroidUpnpServiceImpl.class),         serviceConnection,         Context.BIND_AUTO_CREATE     ); 

but the problem is android activity is blocked. untill the service,

         onServiceConnected(ComponentName className, IBinder service){ ..} 

is called back.so i searched regarding this. i came to know that i have to start my service in new Thread. so please any one help me in doing this.

like image 629
bHaRaTh Avatar asked Feb 28 '11 04:02

bHaRaTh


People also ask

Does service run on separate thread Android?

Service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise.

Can you start a service from background thread?

You can start a service from an activity or other application component by passing an Intent to startService() or startForegroundService() . The Android system calls the service's onStartCommand() method and passes it the Intent , which specifies which service to start.

What is service and thread in Android?

Service : is a component of android which performs long running operation in background, mostly with out having UI. Thread : is a O.S level feature that allow you to do some operation in the background.


1 Answers

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(); 

Also, cache the value returned by bindservice, if any, if you require it for later use.

like image 131
Samuh Avatar answered Sep 21 '22 17:09

Samuh