For my App. I am using the Background service i.e, Lifecycle that excutes for every 200 ms . Now i want the Thread in Service which checks some condition if the lifecycle is on. Can anyone please suggest me how can i implement this logic.
Simply create a Thread in the Service class with come kind of callback. Services are not some magical, remote components of the app, you can create Threads in them just fine. Or even better, go for an AsyncTask instead of Thread, as it has a callback mechanism already implemented (the onProgressUpdate() method) :-)
Related
I have an Android app which uses a service to continuously update a textview in the view when the app is open. It updates it using a broadcast receiver which it sends intents to. By the nature of the app, the service needs to continue to run even after the app has exited/the view is gone. Obviously it's not wise to run the service on the main thread in this case, as that will hog up too much and eventually force close and crash the app. So what is the best way to keep this service running? An ASyncTask? A separate thread? How would I go about doing this? I tried it with an ASyncTask like this:
private class MyTask extends AsyncTask {
#Override
protected Object doInBackground(Object... objects) {
return getActivity().getApplicationContext().startService(intent);
}
#Override
protected void onCancelled() {
getActivity().getApplicationContext().stopService(intent);
super.onCancelled();
}
}
Oh yeah, I'm using getActivity().getApplicationContext() because this is inside of a fragment.
So this works fine; I call MyTask.execute() when I want to start it and MyTask.cancel(true) when I want to stop it, but I'm pretty sure I'm not using it how it should be used. I don't even know what I'm supposed to use as the argument for the execute method (??). And it doesn't seem to be the best idea to just start a service in it and nothing else, surely that would work better using just a thread? What's the proper way to go about this, in order for it to work the way it was intended to? By the way, although this does work for much longer than running it on the main thread, it does still crash after several hours.
You can use async tasks to do background tasks in android. Thread handling on your own is ill-advised unless in specific circumstances. The async task will run in a background thread even the user switches to another view and you can get callbacks at periodic intervals using onProgress() update too. Here are some good tutorials on async tasks to get you started. Please go through them carefully since async tasks will be help you a lot in android development.
http://mobileorchard.com/android-app-developmentthreading-part-2-async-tasks/
http://www.vogella.com/articles/AndroidPerformance/article.html
here are the official docs:
https://developer.android.com/reference/android/os/AsyncTask.html
Update: I think I figured it out. I was way off in what I thought I needed to do, apparently for the kind of service I had I only needed to run it in the foreground (so using the startForeground() method). It seems to be working now. Sorry!
You should not start service in another thread than event thread, instead if some code needs longer time to execute in the service, put that code in another thread in Service Class only.
To execute Service in some other process than the main application, you should define process tag in manifest file, in the service.
Calling startService on background thred does not make the service run on a background thread.
You should call startService normally, without using Async Task.
In your service you should create a new thread to do the work. Here you should not use AsyncTask because this service can run indefinitely, it is not a defined task.
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
Launching a service for first time from its activity like
this.startService(new Intent(this,UpdaterService.class));
does this service runs in a new thread ?
And if I put heavy work load on this service (without taking help of thread) will android will show force close for this application ??
And how different is AsyncTask class from Thread class ??
which one to use where ?
Thanks.
Android developer manual reads:
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).
Service is running in a different process, it's just an application without a user interface. AsyncTask is just a helper class that helps you do some work on a separate thread and synchronize it with your UI thread, for example to show current progress to your users. You can use AsyncTask when you need this type of synchronization, but generally there is no big difference between using any of these. Hope this helps.
I have a question about services: What would be better, create a thread within a service, or service within a thread?
The question comes because I am implementing an error reporter for my application, so that when the application fails it sends me a report with what has happened. My idea is a notification when an error occurs from here show activity Activity and creates a thread to retry delivery until it succeeds or reaches a minimum number of attempts.
Remaking the question, how is the system least likely to remove my process (if out of memory): With a thread within a service, or service within a thread?
I think the best is the first choice, but I saw a code in the same android people, here:
(line 640)
code from google to keep alive a thread??
Where they use the second. What do you think about it?
I don't need an AsyncTask, because I don't need to interact with the UI thread, I'm not showing anything at this point to the user.
Create your worker thread inside the service.
What is the difference between Service, Async Task & Thread. If i am not wrong all of them are used to do some stuff in background. So, how to decide which to use and when?
Probably you already read the documentation description about them, I won't repeat them, instead I will try to give answer with my own words, hope they will help you.
Service is like an Activity but has no user interface. Probably if you want to fetch the weather for example you won't create a blank activity for it, for this you will use a Service.
A Thread is a Thread, probably you already know it from other part. You need to know that you cannot update UI from a Thread. You need to use a Handler for this, but read further.
An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods, and there are three methods that run on UI thread, which is good to update UI components.
I am using Services, AsyncTasks frequently. Thread less, or not at all, as I can do almost everything with AsyncTask.
This is the easiest answer for your question
Thread
is an unit of execution who run "parallel" to the Main Thread is an important point, you can't update a UI component from the any thread here except main thread.
AsyncTask
is a special thread, which gives you helper methods to update UI so basically you can update the UI even AsyncTask will run on a background thread. Interprocess communication handling is not required to be done explicitly.
Service
solve the above problem because it live separate from the activity that invoke it so it can continue running even when the activity is destroyed, it run in the Main Thread(beware of ANR) use a background service (extend IntentService it create the worker thread automatically for you). Service is like an activity without UI,
is good for long task
Few more information I wish someone had told me a few days ago:
You can share global variables - such as threads - between Activities and Services.
Your application together with all its global variables will not be wiped out as long as there is an Activity or a Service still present.
If you have an instance of a Service in your app and the OS needs resources, it first kills your Activities, but as long as there is the Service, the OS won't wipe out your application together with its global variables.
My use case is like this: I have one thread in global space that is connected to a server and an Activity that shows the results. When user presses the home button, the Activity goes to background and a new Service is started. This service then reads results from the thread and displays information in the notification area when needed. I don't worry about the OS destroying my Activity because I know that as long as the Service is running it won'd destroy the thread.
In short, Service for time consuming tasks, AsyncTask for short-lived tasks, Thread is a standard java construction for threads.
From developer's perspective:
Thread: Used to execute the set to codes parallely to the main thread. But you cannot handle the UI inside the thread. For that you need to use Handler. Hadler binds thread Runnable with Looper that makes it a UI thread.
ASyncTask: Used for handling those tasks that you cannot make to work on the main thread. For example, an HTTP request is a very heavy work that cannot be handled on the main thread, so you handle the HTTP request in the ASyncTask It works parallelly with your main thread Asynchronously in the background. It has a few callback methods that are invoked on their corresponding events.
Service: Works in the background under the same Application process. It is implemented when you have to do some processing that doesn't have any UI associated with it.
service is like activity long time consuming task but Async task allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.