Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I start a service in a new thread?

How do I start my service in a new thread. I looked on other questions but it dint work for me. What changes do I need to make in my service when normally running and when running in a separate thread?

like image 657
carora3 Avatar asked Jan 13 '12 14:01

carora3


People also ask

Can you start a service from background thread?

A service is simply a component that can run in the background, even when the user is not interacting with your application, so you should create a service only if that is what you need.

Does service run on separate thread?

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.

How do I start a service with intent?

Start a service. An Android component (service, receiver, activity) can trigger the execution of a service via the startService(intent) method. // use this to start and trigger a service Intent i= new Intent(context, MyService. class); // potentially add data to the intent i.

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. Though conceptually both looks similar there are some crucial differentiation.


1 Answers

Rename your public void onStart(final Intent intent, final int startId) method to _onStart and use this new onStart implementation:

 @Override
 public void onStart(final Intent intent, final int startId) {
     Thread t = new Thread("MyService(" + startId + ")") {
         @Override
         public void run() {
             _onStart(intent, startId);
             stopSelf();
         }
     };
     t.start();
 }

 private void _onStart(final Intent intent, final int startId) {
     //Your Start-Code for the service
 }

For API Levels 5 and Above

public void onStart(Intent, int) was deprecated at API level 5. This should be replaced with public int onStartCommand(Intent, int)

@Override
public int onStartCommand(final Intent intent, final int startId){
    //All code from 'onStart()' in above placed here as normal.
}

private void _onStart(final Intent intent, final int startId) {
     //Your Start-Code for the service
}
like image 148
theomega Avatar answered Sep 29 '22 09:09

theomega