Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why my service block the UI?

Tags:

android

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?

like image 288
dinesh707 Avatar asked Jun 19 '12 10:06

dinesh707


3 Answers

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.

like image 57
Mukund Samant Avatar answered Sep 28 '22 05:09

Mukund Samant


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.

like image 42
Siddhesh Suhas Sathe Avatar answered Sep 28 '22 04:09

Siddhesh Suhas Sathe


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

like image 30
Dr Glass Avatar answered Sep 28 '22 06:09

Dr Glass