'Why does my Android service block the UI?

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?



Solution 1:[1]

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.

Solution 2:[2]

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

Solution 3:[3]

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.

Solution 4:[4]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Siddhesh Suhas Sathe
Solution 2 Dr Glass
Solution 3 ScouseChris
Solution 4 Hamza Hmem