Running a Service from ASyncTask or Thread? - android

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.

Related

How to Keep AsyncTask when user closes app

This is in my main activity:
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
moveTaskToBack(true);
System.exit(0);
}
I want the AsyncTask to continue put data in my server in the background after the user closes the app.
I want the AsyncTask to continue put data in my server in the background after the user closes the app.
The purpose of AsyncTask is NOT to perform background tasks that's beyond the scope of an Activity's lifecycle. When a background thread is assigned from a thread pool, it expects to return it once the task is over. ie you cannot use an AsyncTask for which the required time is indefinite.
What you are looking for is Services in Android .
Why even use AsyncTask if we have services?
Well, say for instance you require to download an image/song from an Activity on click of a Button or you need to perform a task that would take some time to finish its execution. Performing these tasks from the Main thread(aka UI thread) is a bad approach and would make your app sluggish and eventually can lead to an ANR. So these tasks are to be processed asynchronously from a separate thread to keep the app butter smooth.
Services is one part of a solution, but note that a service runs on the foreground thread. You would want to run your AsyncTask from the service to ensure that it continues to run on a background thread.
Personally, I would recommend against using a service in favor of the JobScheduler or if you need to support devices below API 21, Evernote's JobManager (which is also a bit easier to use). These will help you schedule your background operations at appropriate times, to minimize battery use or when the device is idle. It's important to be a good citizen when using the device's resource.
You have to check Services or/and IntentServices

Thread in Service Android

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) :-)

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

Why is it important to use Services for background tasks?

I know I should use Services in Android to do stuff in the background from a non-UI thread.
However, I would like to know what is wrong with just spawning a background thread to do the work from an Activity class (within an onClick event for example).
Thanks in advance.
Actually, Services are used for long running tasks, especially those, that run when your activity is not running. Threads can be used for making some tasks inside your activity. This states, that a Thread, created inside your Activity, can not live outside of the activity that's created it, when a Service can. Hope this helps.

Does service launched from its activity runs in a new Thread?

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.

Categories

Resources