Home » Android » android – How do I start a service in a new thread?

android – How do I start a service in a new thread?

Posted by: admin June 15, 2020 Leave a comment

Questions:

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?

How to&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
}

Answer:

I do not think you can start your service in a new thread, but what you can do is start a new thread in your service.

This is because like the activity, the service has life cycle methods that run on the main thread.

So your service will run on the main thread but it will do the heavy lifting on a new thread that it creates when ever it needs to.

I hope it helps..

Answer:

Citing from http://developer.android.com/reference/android/app/Service.html

“Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work. More information on this can be found in Processes and Threads. The IntentService class is available as a standard implementation of Service that has its own thread where it schedules its work to be done.”

Answer:

In my project, i have someone like this and it’s work:

Thread welcomeThread = new Thread() {
@Override
public void run() {
    try {
        super.run();
        while (isMyServiceRunning() != true) {
            sleep(100);
        }
    } catch (Exception e) {
        System.out.println("EXc=" + e);
    } finally {
        Intent i = new Intent(getApplicationContext(), MainPage.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
    }
}
};

welcomeThread.start();