Android: running a thread in background - android

is there any way to leave a thread in background when i close the app in android? I read about a Service but implementing it is too much than i need. Thanks

Hi, is there any way to leave a thread
in background when i close the app in
android?
That will happen by default. That does not mean it is a good idea.
I read about a Service but
implementing it is too much than i
need.
More likely, it is precisely what you need.
If you start a thread in an Activity, then fail to stop that thread, it will run forever, until Android terminates the process, since you have no way of stopping it. The only sort-of acceptable exception is if your thread stops itself, and then you have to be very very careful that it actually does terminate cleanly. On the other hand, you can arrange to stop a running Service whenever you need, from any Activity, and that Service can arrange to stop the thread, so you don't leak the thread indefinitely.
I strongly encourage you to implement a service that manages the thread.

Another reason to use a Service is that the platform will give the process priority to NOT be killed while it is in the background.

Related

Why use Service if it runs in the same thread in android

I was going through Bound Service in Android Developer website. I thought I understood the service enough but I just found another way of connecting service through Using a Messenger class especially for local service. There I got confused. Maybe I got the concept wrong.
Here is my understanding of Android Service. You create a service when
You want to do separate jobs in the background.
You want to make it a separate process.
You want to make it run in a lifecycle that's independent of the component that started it.
Confusion is the first item in the list, the definition of the background. Isn't the background a thread or process? I never thought that it can run on the main thread.
Here is the caution of service in the dev pages about.
Caution: A 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). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.
Questions
Why does one choose to use service if the service function will anyway run on the main thread?
Do we have to write a service only to block ANR even if the time-consuming job is done in the main thread? Assume the service is only for my application.
Are there any practical cases or reasons to use a service as private and running in the same thread?
Application main thread is not always the UI thread. For example, when Activity is stopped, the onStop() is invoked, hence the UI thread is taken away from that Activity and moved to another Activity within the same or a different application. However it doesn't mean the application is no longer active, it can continue working in the background until it is closed either by OS or by user. Then who keeps it running in the background? It is the main thread and not the UI thread.
What are services
In Android, a Service is an application component that can perform
long-running operations in the background on the UI thread. By
background, it means that it doesn’t have a user interface. A Service
runs on the main thread of the calling Component’s process by default
(and hence can degrade responsiveness and cause ANRs), hence you
should create a new Thread to perform long running operations. A
Service can also be made to run in a completely different process.
Unlike Activity components, Services do not have any graphical
interfaces. Also Broadcast Receivers are for receiving broadcast
messages (broadcast, multicast, unicast) and perform short tasks
whereas Services are meant to do lengthy processing like streaming
music, network transactions, file I/O, interact with databases, etc.
When a Service is started by an application component like an Activity
it runs in the background and keeps running even if the user switches
to another application or the starting component is itself destroyed
Why use service
Services are given higher priority than other Background processes and
hence it’s less likely that Android will terminate it. Although it can
be configured to restart once there is ample resources available
again. You should go through the different processes and their
priority/important level in the documentation on processes and
threads. Assigning them the same priority as foreground activities is
definitely possible in which case it’ll need to have a visible
notification active (generally used for Services playing music).
Use IntentService if you don't want to fiddle with managing threads on your own. Otherwise, use AsyncTasks.
Please read this excellent article to understand more in detail and also read this answer.
Service basically runs in UI thread or main thread.But,if we are going to perform long running operations in service,we need to create a background thread and perform that task.
But why we have to use service?
Now let's think of Music Application.We need songs to be played continuously even if we leave music app.If we use activities,we can't achieve above requirement.So,service helps in these kind of scenarios.Even if the app is not in foreground, service keeps on running and we are able to listen to songs.This is why we use service even though it runs on main thread.
In short, Services runs on the background of the UI thread.
You can perform tasks like client-server authentication or write to a database where the tasks are done in the background with no graphical interface.
But if you're doing a really long processing tasks that could freeze the interface, you use a service on a separate thread.
eg of a Service on a separate thread is IntentService

understanding Android Services and threads

I have doubts when it comes to Services.
I know the service runs in the background, but I thought you necessarily needed to create a thread within the service, otherwise it would block the main thread and you would get an ANR error.
I thought I got it! But then I read this in the Android Developer guide:
…if your service performs intensive or blocking operations while the user interacts with an activity from the same application, the service will slow down activity performance. To avoid impacting application performance, you should start a new thread inside the service.>
The paragraph mentions "intensive or blocking operations", but doesn’t mention an ANR error, it mentions performance. So how a service works?
Supposing an Activity starts a Service. Does the Service run by default in the background of the main thread? Meaning that you can still use your activity while the service is running, but since your Activity and the Service are sharing the main thread’s resources, it would slow down the performance of your activity, and if Service is doing CPU intensive work, it could leave no resources for the activity to use, and eventually you would get an ANR error.
The best practice (but not necessarily, if the service is doing light work) would be to start a new Thread within the Service, now the Activity and the Service are using their own thread’s resources. Then you could close your activity, but Android keeps the service thread alive.
Is that it? Thanks =)
I thought you necessarily needed to create a thread within the service, otherwise it would block the main thread and you would get an ANR error.
Correct.
The paragraph mentions "intensive or blocking operations", but doesn’t mention an ANR error, it mentions performance.
Feel free to file a bug report at http://b.android.com to get them to improve this portion of the documentation. :-)
Does the Service run by default in the background of the main thread?
The lifecycle methods of a Service, such as onCreate() and onStartCommand(), are called on the main application thread. Some services, like IntentService, will provide you with a background thread (e.g., for onHandleIntent()), but that is specific to that particular subclass of Service.
and eventually you would get an ANR error.
Yes.
The best practice (but not necessarily, if the service is doing light work) would be to start a new Thread within the Service, now the Activity and the Service are using their own thread’s resources. Then you could close your activity, but Android keeps the service thread alive.
Basically, yes. Here, "light work" should be less than a millisecond or so. Also, some things that you might do are naturally asynchronous (e.g., playing a song via MediaPlayer), so it may be that the Service itself does not need its own thread, because something else that it is using is doing the threading.

Android NonUI Thread making application "not respond"

I am editing the code of an android app that is making GPS calls in a service. LocationListener. It also uses ServiceConnection
In some views the device decides that my application is taking too long to respond, and that the user can either "Force Close" or "Wait". Before this popup appears, the application is still usable by the user, they can scroll, slide, press buttons etc.
I am only assuming this is related to the GPS service as it is running whenever this problem happens.
I heard that this problem has to do with a thread running on the UIthread, instead of a background thread. But I was sure that services run asynchronously in the background thread.
Insight appreciated
Using a service does not necessarily spawn a new thread, the service call runs on it's caller thread. From the android API Service doc at:
"Note that services, like other application objects, run in the main thread of their hosting process..".
You can specify the service to run on a different process but best practice is to spawn a new thread in the service.
More on android service at:
http://developer.android.com/reference/android/app/Service.html
I fully recommend you to extend AsyncTask,it enables proper and easy use of the UI thread. Allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. You may want to do all the computing in doInBackground method.BTW Force Close or Wait is a classic behavior for this kind of issues.
Good Luck!!!
Processing in a service can still cause your application to hang.
The solution you should be looking at implementing is to run any logic that may bog down your activity in a separate thread. This includes things like: Database updates/insertions, Network communication, and any other pieces of long running code.
The AsyncTask is a convenient method for this as you can manipulate the UI in the onPreExecute and the onPostExecute functions.
You can implement an AsyncTask directly in your service as a subclass.
Hoepfully this helps!
Cheers

Difference between Android application spawning thread vs. Service?

I have an Android application that has a need to perform work in the background and on a separate thread. For my first proof-of-concept I subclassed the Application class and inside onCreate() I spawn a Thread that does the background work. This works just great. However, I just realized that in the past I've used a service for situations like this.
The question is, is there a reason to do work on a Thread spawned from a Service instead of a Thread spawned by Application.onCreate()? The Service is supposed to perform "background" work (it uses the UI thread unless a Thread is used, I know) that is independent of the Activity and can run while no Activity is visible. Using an Application-based thread seems to accomplish all this just as well. By not using a Service it actually removes complexity because the Activity just accesses the Application singleton. As far as I know I have no need to bind to the Service.
Will I get bit by lifecycle corner cases that using a Service would prevent? That's the only concern I have over this approach, but otherwise I'm not sold on the benefits of a Service.
The difference would be if you want the thread to run in the background only when the Activity is running or if you want it to continue to run when the user leaves.
Services are capable of running in the background even when the Activity is no longer available. They are intended to be used when your app should continue to do work without any user involvement in the near future. If you run the Thread in the Service, the thread will continue to run even when the user leaves the app. This can be beneficial sometimes as the user may want you to keep downloading a really large file but doesn't want the app to continue to run in the foreground. Then, a few hours (days, months, years) later the user can re-enter the app to read the file.
If, however, you're using a thread that needs to constantly update the UI based on results, it may be more beneficial to launch it within the Activity since it has no real purpose to run in a Service. It also may be easier in your program for your Thread to talk to the UI if it's in the Activity rather than the Service. (There may be some performance benefits as Android doesn't have to handle yet another Service on it's list, but that's purely speculation on my part. I have no proof of it.)
NOTE: Threads created in Activities will still continue to run even when the Activity quits. However, this is merely because the app is still in memory. The Activity and it's thread are on a higher priority to be deleted from memory than a Service thread when the Activity is no longer within view.
If your application is not either in the foreground, or visible, then it's more likely to be killed off by the system. If you run your code as a service, rather than a thread spawned by a background process, then your task will survive for longer. No guarantees, so you still need to manage the process lifecycle properly, but running as a service is likely to give more reliable results.
See http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html

Thread started by an application in android

If I raise a thread in via an Application in Android, how long does the thread life and is active?
Does a thread continue to live when the user leaves the application. If so for how long?
Until the Thread completes. You should look into AsyncTask class instead of regular Threads though.
Yeah in Android threads are like the old-fashion Java thread. They do not have a predefined lifecylvce like Services, Activities etc. If you start a new thread you must also be responsible of its lifecycle (i.e. terminate it when you do not need it anymore and keep it alive untill you need it).
EDIT: see here and this other question. As I was saying, the thread remains alive untill it has work to do. Regard that if the process of your application is destroied by the O.S. then also the thread you have created will be destroyed as well.

Categories

Resources