What to use: service or threads - android

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.

Related

What is the best practice for always running networking android app?

I am implementing app that is going to be always running and connected to server.
So the tablet has nothing to do other than running this app, and checking the server all the time for updates to show on the screen.
What can be the best practice to keep the app always running and connected?
In my experience, i have 2 options to solve this problem:
Service always running and connected to my activity to keep it updated.
Keep the work in threads within the activity, since the activity will stay always on. The app will be always on.
My questions are:
What is the best practice for keeping the app running all?
What is the best practice to keep the app connected ? Threads within activity? or service connected to activity?
Is there any preferable structure for such application type?
thank you
Battery is something that i will always take into consideration especially when networking task has to be done. So analyze the point where the is absolute necessary to connect to server.
Whenever you server needs to contact the device use GCM push notification that will save your battery juice which you will spend in polling the server
Well for
Service v/s Thread
is concern the use service in which you should spawn worker threads which will perfrom the networking task
these threads will notify the main service thread when they are done for that you need to user Handlers in android
i will favor service over thread because if you close the activity network request will still be fulfilled once request is complete save it in some storage form(database/share pref/content provider) and retrieve it from them. Once you are done dont for get to destroy the service by all stopSelf a appropriate point or else the service will keep exhausting you phone resource. which will make you app a bad citizen.
A simple implementation of the about pattern i mentioned is IntentService which will automatically spawn the worker thread i.e you just have to override handleIntent method and do all the heavily lifting there which will not be on main thread. And IntentService kills it self when if finds itself doing nothings
The question which you have asked to my understanding is related to syncing with server you can find more about in from android docs
http://developer.android.com/training/building-connectivity.html
If you read the official docu from Android. The best solution is using a service for your kind of app. It's prepared to run continuosly in background. You can implement it to check the network in a transparent way and you can bind the information to another activity. Furthermore, it's more scalable if later you want to change your connection or requirements (it won't affect to your apps activities).
EDIT.
The good point is, that if someday for a reason your app is not in foreground. The service can still be running. Services are prepared for long running tasks http://developer.android.com/guide/components/services.html

Execute long running operations on the service

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.

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.

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