5

I created a service (service B) from Activity (Activity A). And from service B, i created another service (service C). previously the service C used to be a thread not a service. Since it has problems in the long run i changed it to a service. The service C runs a while loop with 3 second Thread.sleep calls. But general condition it do not stop. The Log shows the service is running. But the UI is blocked and after few mins system ask me whether to shut down.

How to make this service non blocking call?

tonylo
  • 3,311
  • 3
  • 28
  • 27
dinesh707
  • 12,106
  • 22
  • 84
  • 134

5 Answers5

3

From the service documentation in Android

A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.

A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

The best way in this case is to start a new thread and then call a service from there.

Mukund Samant
  • 1,079
  • 7
  • 12
3

Yes, from the documentation, it's clear that services are not separate processes. Instead, please follow below to make it work:

  1. Start a service from wherever you want to start
  2. In service's class you wrote, write another private class extending thread which will make sure all your background stuff will run in a background thread which is separate from a mail process
  3. Start a thread from onCreate method of service's class. If you start your background work in onStartCommand, you may accidentally start multiple services doing the same task. Ex. You've given a button on your activity which will start background service. And if you happen to click it multiple times, it'll start those many number of services in background.

    Thus, if you use override onCreate method from service, it will check if the service is already running or not and if it's not running, it'll start the service. Otherwise it'll skip and won't start another service.

2

I think that service C is running on main thread, try create another thread (new thread or asynctask)

Dr Glass
  • 1,487
  • 1
  • 18
  • 34
0

Services always run on the main thread. You need to spawn a background thread or repeatedly run a TimerTask etc in your Service C to avoid blocking the UI thread.

ScouseChris
  • 4,377
  • 32
  • 38
0

You can start your service in a separate thread like so:

Thread newThread = new Thread(){
   Intent serviceIntent = new Intent(getApplicationContext(), YourService.class);
   getApplicationContext().startService(serviceIntent);
 };
 newThread.start();

Please refer to this comment.

Hamza Hmem
  • 502
  • 5
  • 11