Execute long running operations on the service - android

I'm building an application which have a Service. I know that all application components run in the same UI process, at least you specify it in the manifest. So to avoid ANR's messages i have three ways.
Specify the service in the manifest to run in a separate process like
android:process=":remote" but i've read some StackOverflow's post that
says that it's not a good idea, because it consume a lot of battery and cpu processing.
That i really respect since those post are from trusted people.
Use an IntentService. it's probably a good way out. but i need my service running even if the
activity isn't visible. Because i need the service keep checking against a web service for new
messages from other users and notify thru Notification. Could it be posible using a
an IntentService? is that an ellegant solution.
Use a local service. just removing the android:process=":remote" attribute from the manifest file.
But i get some ...OnMainThreadException errors. it means that i need to create an special
thread to execute those long running operations or use AsyncTask,
maybe there are another ways to do it. please let me know, how to execute long runnig operations on the service. is really imperative.
thanks.

Android Service executing in UI thread. So you should use AsyncTask or another way to work with threads for network requests.

First of all, let's accept that there 2 parts: an active part (the networking) and some sleeping part before the next active part. I think you can use a plain local IntentService for active parts. Each active part on its completion should reschedule the next active part using AlarmManager. This approach makes sure your app does not consume resources during sleeping parts. You are right - once the IntentService gets a result to be presented to user it can use Notification.

Related

An Android Service constantly performing some different jobs depending on each other

I want to constantly, without stopping, perform 2-3 kinds of operations from my Service in Android. That is:
check if some hardware is connected and retrieve the data from it every 1 second and save it to the files
send those files a server
perform some calculations
The second job depends on the 1st one.
Note that the Service will have GUI as well if that matters, but the GUI will be used rarely. Most of them time the Service will work in "background" doing what it has to do.
How can I do that? Should there be 3 different threads or what? Or I don't need the thread because it'll be a service?
Any help is appreciated.
If you want to perform all operation in parallel in background then use android service and use ScheduledThreadPoolExecutor class to achieve this.
Otherwise use timer or Executor(with onr thread) inside android service to perform all operation in serial manner.
Let me know, This is helpful for you?
That depends on what type of service you are using, Intent Service or Service.
If you are using Intent Service, then you don't have to worry about creating a new thread, as it itself creates a worker thread.But, just keep in mind that, it takes one care of requests one at a time, in queue manner and stops itself when the processing is done.
But if you want to perform simultaneous request at once, extend from Service. You will have create a worker thread to run this service as it doesn't create a separate thread.
Check developer guide for more info:
https://developer.android.com/guide/components/services.html
To communicate between two services, you have to make use of Broadcast Receiver to receive intents which you can send from your first service or use listener callback, but i would suggest you to use Broadcast Receiver and intents.

Is it better to use AsyncTask (Or Timer) within single process, or using Service in separate process?

I just read Android Architecture Tutorial: Developing an App with a Background Service (using IPC). It is basically
Have a service run in separate process.
A repeated timer event will occur in the service.
Within the timer event handler, it will perform networking to retrieve tweet, and inform all the listener attached to it. Listeners are attached to it through IPC.
I can see there are 2 major characteristics with this approach.
Tweet retrieving action run within separate process.
It always run, even the main activity has quit.
However, if "It always run" is not my requirement. I want everything to stop when I quit my main Activity.
Will it be better, if I use AsyncTask (Or Timer) within my main Activity, to perform tweet retrieving action? Everything will be run within single process. No more using Service.
Using AsyncTask (Or Timer), seems simpler. We no longer need to deal with IPC.
Or, using Service approach might be better? Am I missing some goodies provided by Service?
Using service is a better approach as it will allow you to perform the polling independent from the application flow.
As it is a task where no user interaction is required and it has to be done in the background without disturbing the main UI of application and whatever the user is doing, a service is an ideal candidate for its implementation.
It is possible to bind the service with the application in such a way that when the main application terminates, it will also turn off the service.
I would take the view that a TimerTask can be set to execute and repeat at a given interval, Timers run on a separate thread so all this work would occur in the background without disturbing the UI. It would be easy for you to trigger an update within your app when the TimerTask completes and update the UI when you want.
When you exit the app it's a simple case of calling cancel() on your Timer and the purging all the tasks with purge().
Nice and easy and you don't need to implement IPC, which can be very fiddly to get right.
EDIT
Using AsyncTask you can do pretty much exactly the same thing but you'll have to manually schedule the next run. I have used both solutions in the past and found them to work equally well so it's all down to your preference.
At first you have to know, that a service isn't a Thread. If a activity binds a Service and runs as a Deamon, but a ASynchTask is another thread.
ASynchTask's are designed for doing some work which should not running on UI-Thread (for example processing some larger calculations)
Services are designed to run permanantly on Background.
If you want to permanantly check for new tweets, even if your activity is stopped or paused, you should use a Service, which checks into an own thread for new data.
TimerTask are good old java style implementations which run on their own thread.
You can used them for processing some data, but you'll have some problems to manipulation UI. If you want to be it on propper "AndroidWay", use a Handler instead of TimerTask.
First of all, I know the tutorial you are following...I've followed that tutorial myself while trying to learn IPC. One thing you need to know is, The Android docs explicitly say,
Note: Using AIDL is necessary only if you allow clients from different applications to access your service for IPC and want to handle multithreading in your service.
If at all possible, you should just bind to the service.
Also, you must consider, do you really need a service? Consider that the Android Twitter app doesn't even refresh tweets for you, its on an as needed basis. Polling can be battery intensive, so you must consider if this is really necessary.
Also, will you be using these tweets from multiple activities? If so it would be nice to not duplicate the code in multiple places. So maybe you do want a service in this case.
Other than that, I would recommend that you start simple (Async task with a timer to update it), and move to a service if you think you need it.

Why would one use AsyncTasks when you can use Services?

When you learn to develop for Android, you learn that if there's any type of process -that takes more that 5 seconds- running inside the ui thread, the system will show the infamous ANR message. That's when they introduce the evil monster... AsyncTask. At first you see this class as your savior, but then you realize it's the biggest problem in development... Handling rotation or ui events becomes so problematic, it's even painful.
What do you guys think about it... are AsyncTasks worth the trouble? Any other method that makes it less of a problem to perform long running tasks regardless of screen rotation?
I guess you'll probably say, hey why don't you just make it a Service... Yeah that's a solution, but then let's go to my real question. Why don't we just use services and stop using AsyncTasks completely... Are they useful at all?
While developing it is always good to choose the suitable component for the execution. You need to clear your requirement and according to it you can choose between a Service or an AsyncTask.
A service is an Android component that lives independently from any other components. Activities may come and go, but services can stick around, if you wish. They serve a number of roles, from managing state that multiple activities rely upon to serving as cron jobs to handling longer app widget updates.
AsyncTask is a class that arranges to do some work off the main application thread. From the implementer and user of the AsyncTask, how it performs that bit of magic is not generally important. In reality, it uses a thread pool and work queue. AsyncTask uses a Handler to help arrange for select bits of work to be done on the main application thread (e.g., notifying the user of progress updates).
For more clarification see the difference between them.
AsyncTasks and Services are not peers. Either might invoke the other, their purposes are different. I have just a few things to add to Lucifer's answer.
A key thing to remember is that if your process is in the background, hosts a Service, and is killed, that Service will be reincarnated at some point. This is not the case for an AsyncTask that may be running in a process when it is killed. This means that work being done in a Service is guaranteed to make forward progress in the future (although its not guaranteed when). If you have work that must be done, better to do it in a Service.
Calls to Service.onStart and Service.onStartCommand happen on the process' main thread. If you block this for a long time, you'll get the same "app not responding" dialog. As a result, an AsyncTask can be a great thing to use inside a Service to do the real work.
I tend to use AsyncTasks initiated from an Activity for things related to the UI. These are often things that aren't required work and whose work can be easily redone in the future. For example, this might be reading a bunch of images off disk or make a calling to a web service to see if the user has any notifications. This work can be done again, and if the UI is destroyed because the process is killed the work probably needs to be done again anyway.
If on the other hand you want to say upload a group of photos to the web as soon as possible, I'd farm this out to a Service which will use one or more AsyncTasks to do it. This is work I want to get done and want to be resumed if it gets interrupted. If you're going to use a Service, consider using an IntentService so that your Service stops when its work is done.

What to use: service or threads

I am developing an android app which fetches/uploads data from/to the web service every n minutes. This upload/download is only done when the app is running. But this might change in future.
I dont update the UI when the new data is downloaded. The UI is only updated if the user is on the current screen(app have multiple activities)
My question is what is the best approach to this problem.
I dont think service is the right approach as it sounds like an overkill(in the present scenario). AlarmManager could be an option.
Running threads inside a service be an option ..something like this .
Any pointers/suggestions would be great.
Thanks
I am using AsyncTask in my activity to ask .net web service some information and it works and easy to use.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
Well, in this case, since the app would already be running during the time, either would work great, but a service can be called from anywhere within the application so this is where I would use the service over the thread.
If you want to create the thread to only be used in lets say Main.java, then thread would work fine, these are the only things that I can see really making ANY difference at all, they're really pretty close, and in this case neither gives a distinct "correct" answer, but I would choose Service
I think all approaches you noted would work ok. Personally I'd go with this:
Use AlarmManager to wake download service. Start it when Activity is shown, stop it when activity hidden.
Download service should be short lived: start it to do the upload/download and then shut it down.
If download service does get some new data, it sends a Broadcast which Activity listens to.
Just broadcast a message after your upload/download is done, and then have a receiver start the service and then have that service stop itself. And you are done.
This should be done if you dont plan on polling the server for new information or anything. Primarily this kind of approach would be for onetime update, interpret, finish. And wait until the next update. Which primarily for most cases is streaming.. but depends on what you are getting.

Android - Run in background - Service vs. standard java class

In Android, if I want to do some background work, what is the difference between
Creating a Service to do the work, and having the Activity start the Service
VS.
Creating a standard java class to do the work, and having the Activity create an object of the class and invoke methods, to do the work in separate thread.
Doing your own threads is overkill, there are solutions for this, so you don't have to worry about the hard parts of concurrency. Have a look at AsyncTask or IntentService. If you go for a service please keep in mind that your service can be killed at any time.
Well, Android provides some useful methods for making worker threads easily. Look at the Looper class definition. It allows you to send events via a Handler to be executed one after another in another thread or transmit messages between different threads.
A service is nothing fancy. Creating a Service is just a way of telling the OS that you need to do some work even when your Activity is not visible.
Depending on the application you're building it might not be an option.
Nearly every network application will have some of its functionality on a Service to allow the user change active Activity while something is being downloaded.
In an RSS reader, for example you can click 'Update all' and, depending on the current data connection, it might take a bit longer than you wish. So if you want the user to be able to get back to the Home screen and do anything else while the files are being dowloaded you'll have to use a Service.
A Service allows you to run tasks on the background while the user is not on your Activity. This doesn't mean it'll be running all the time. Check the Service lifecycle.
BTW IntentService is a service.

Categories

Resources