Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run a service on a separate thread?

I need to run a service on a separate thread. This is because it accesses a webservice which can take 5 - 10 seconds, and I don't want to get ANR. I will also be binding to this service. I have found a way to launch the service in a separate thread with something like:

Thread t = new Thread(new Runnable() {

            public void run() {
                //Launch and/or Bind to service here
            }
        });
        t.start();

However I believe this only runs the starting code in a new thread while the service itself runs in the main thread. So how would I actually run all the code from the service in another thread?

Thanks in advance

like image 898
RomanP Avatar asked Apr 23 '11 15:04

RomanP


1 Answers

You can use a IntentService

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work

http://developer.android.com/reference/android/app/IntentService.html

like image 129
aromero Avatar answered Nov 04 '22 02:11

aromero