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?
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.
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.
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.
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.
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
}
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