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

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.

Related

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.

Android service runing in background and changing service logic through some UI, how to do that?

I am new to android development. I am creating an android application, in which there is a background service always running..
The service's target is to monitor incoming sms messages and do processing based on message filter
However the user would also want to change service bahviour through some UI/Activity. for exmaple user might wanna change the message filter.
SO in this case would my Service and Activity run as one process or seperate process ?
How would I make them communicate ? Please advise best possible model so that the performance is not affected.
Second question: Does an apk always have one processes or can have multiple processes ??
Thanks,
By default, all components of your application run in the same process, but it is possible to arrange for different components to run in different processes by using the android:process attribute in the manifest xml. I would strongly recommend against this for what your are doing.
You will want your Activity and Service to run in the same process, but the Service should arrange to have it's own thread to do processing on, otherwise the Service will run in the main UI thread, which you definitely don't want.
You could use the IntentService class to allow your activity to post Intent's to your Service.
The IntentService class then queues the Intents up and processes them one at a time on a dedicated worker thread that is managed by IntentService.
You might want to look at a Bound Service That page describes how an activity can access methods within a running service in the section 'Extending the binder class'

timer for a social app

I am writing a social game but am stuck with how to create a timer thread that works accross activities showing time lapse for an attribute such as energy. Every activity has the energy textview but the thread can update only one view at a time. Please note that im not using androids timer class but have created my own thread class.
You probably don't want to try to keep a thread running between activities. Managing it when the activity suspends will give you nothing but headaches. It's much easier to just store your time in the Application while you move from activity to activity. The Application is alive for the duration, no matter which Activity is actually loaded. The fact that you have an identically named TextView in various activities is neither here nor there... it's not the "same" TextView... it just looks (and smells) similar. So, you can just grab the clock when the app first launches and at any given time look at the difference between the current time and that time.
Then just use a Timer to update the string in whatever Activity you're in.
If you're unfamiliar with Application it's going to be a real Eureka thing for you to discover (Android tutorials overlook it ALL the time, for some reason, leaving you to do all sorts of really ugly Intent passing alternatives).
If you have any questions on how to use it, just follow up in a comment, and I'll add details.
I think you must think about using a Service :
Thus a Service itself is actually very simple, providing two main
features:
A facility for the application to tell the system about something it wants to be doing in the background (even when the user is not
directly interacting with the application). This corresponds to calls
to Context.startService(), which ask the system to schedule work for
the service, to be run until the service or someone else explicitly
stop it.
A facility for an application to expose some of its functionality to other applications. This corresponds to calls to
Context.bindService(), which allows a long-standing connection to be
made to the service in order to interact with it. When a Service
component is actually created, for either of these reasons, all that
the system actually does is instantiate the component and call its
onCreate() and any other appropriate callbacks on the main thread. It
is up to the Service to implement these with the appropriate behavior,
such as creating a secondary thread in which it does its work.

Android: AsyncTask vs Service

Why do I read in the answer to most questions here a lot about AsyncTask and Loaders but nothing about Services? Are Services just not known very well or are they deprecated or have some bad attributes or something? What are the differences?
(By the way, I know that there are other threads about it, but none really states clear differences that help a developer to easily decide if he is better off using the one or the other for an actual problem.)
In some cases it is possible to accomplish the same task with either an AsyncTask or a Service however usually one is better suited to a task than the other.
AsyncTasks are designed for once-off time-consuming tasks that cannot be run of the UI thread. A common example is fetching/processing data when a button is pressed.
Services are designed to be continually running in the background. In the example above of fetching data when a button is pressed, you could start a service, let it fetch the data, and then stop it, but this is inefficient. It is far faster to use an AsyncTask that will run once, return the data, and be done.
If you need to be continually doing something in the background, though, a Service is your best bet. Examples of this include playing music, continually checking for new data, etc.
Also, as Sherif already said, services do not necessarily run off of the UI thread.
For the most part, Services are for when you want to run code even when your application's Activity isn't open. AsyncTasks are designed to make executing code off of the UI thread incredibly simple.
Services are completely different: Services are not threads!
Your Activity binds to a service and the service contains some functions that when called, blocks the calling thread. Your service might be used to change temperature from Celsius to Degrees. Any activity that binds can get this service.
However AsyncTask is a Thread that does some work in the background and at the same time has the ability to report results back to the calling thread.
Just a thought: A service may have a AsyncTask object!
Service is one of the components of the Android framework, which does not require UI to execute, which mean even when the app is not actively used by the user, you can perform some operation with service. That doesn't mean service will run in a separate thread, but it runs in main thread and operation can be performed in a separate thread when needed.
Examples usages are playing music in background, syncing data with server in backgroud without user interaction etc
AsyncTask on other hand is used for UI blocking tasks to be performed on a separate thread. It is same like creating a new thread and doing the task when all the tasks of creating and maintaining the threads and send back result to main thread are taken care by the AsyncTask
Example usage are fetching data from server, CRUD operations on content resolver etc
Service and asynctasks are almost doing the same thing,almost.using service or a asynctask depends on what is your requirement is.
as a example if you want to load data to a listview from a server after hitting some button or changing screen you better go with a asynctask.it runs parallel with main ui thread (runs in background).for run asynctack activity or your app should on main UI thread.after exit from the app there is no asynctask.
But services are not like that, once you start a service it can run after you exit from the app, unless you are stop the service.like i said it depends on your requirement.if you want to keep checking data receiving or check network state continuously you better go with service.
happy coding.
In few cases, you can achieve same functionality using both. Unlike Async Task, service has it's own life cycle and inherits Context (Service is more robust than an Async Task). Service can run even if you have exited the app. If you want to do something even after app closing and also need the context variable, you will go for Service.
Example: If you want to play a music and you don't want to pause if user leaves the app, you will definitely go for Service.
Comparison of a local, in-process, base class Service✱ to an AsyncTask:
✱ (This answer does not address exported services, or any service that runs in a process different from that of the client, since the expected use cases differ substantially from those of an AsyncTask. Also, in the interest of brevity, the nature of certain specialized Service subclasses (e.g., IntentService, JobService) will be ignored here.)
Process Lifetime
A Service represents, to the OS, "an application's desire to perform a longer-running operation while not interacting with the user" [ref].
While you have a Service running, Android understands that you don't want your process to be killed. This is also true whenever you have an Activity onscreen, and it is especially true when you are running a foreground service. (When all your application components go away, Android thinks, "Oh, now is a good time to kill this app, so I can free up resources".)
Also, depending on the last return value from Service.onCreate(), Android can attempt to "revive" apps/services that were killed due to resource pressure [ref].
AsyncTasks don't do any of that. It doesn't matter how many background threads you have running, or how hard they are working: Android will not keep your app alive just because your app is using the CPU. It has to have some way of knowing that your app still has work to do; that's why Services are registered with the OS, and AsyncTasks aren't.
Multithreading
AsyncTasks are all about creating a background thread on which to do work, and then presenting the result of that work to the UI thread in a threadsafe manner.
Each new AsyncTask execution generally results in more concurrency (more threads), subject to the limitations of the AsyncTasks's thread-pool [ref].
Service methods, on the other hand, are always invoked on the UI thread [ref]. This applies to onCreate(), onStartCommand(), onDestroy(), onServiceConnected(), etc. So, in some sense, Services don't "run" in the background. Once they start up (onCreate()), they just kinda "sit" there -- until it's time to clean up, execute an onStartCommand(), etc.
In other words, adding additional Services does not result in more concurrency. Service methods are not a good place to do large amounts of work, because they run on the UI thread.
Of course, you can extend Service, add your own methods, and call them from any thread you want. But if you do that, the responsibility for thread safety lies with you -- not the framework.
If you want to add a background thread (or some other sort of worker) to your Service, you are free to do so. You could start a background thread/AsyncTask in Service.onCreate(), for example. But not all use cases require this. For example:
You may wish to keep a Service running so you can continue getting location updates in the "background" (meaning, without necessarily having any Activities onscreen).
Or, you may want to keep your app alive just so you can keep an "implicit" BroadcastReceiver registered on a long-term basis (after API 26, you can't always do this via the manifest, so you have to register at runtime instead [ref]).
Neither of these use cases require a great deal of CPU activity; they just require that the app not be killed.
As Workers
Services are not task-oriented. They are not set up to "perform a task" and "deliver a result", like AsyncTasks are. Services do not solve any thread-safety problems (notwithstanding the fact that all methods execute on a single thread). AsyncTasks, on the other hand, handle that complexity for you.
Note that AsyncTask is slated for deprecation. But that doesn't mean your should replace your AsyncTasks with Services! (If you have learned anything from this answer, that much should be clear.)
TL;DR
Services are mostly there to "exist". They are like an off-screen Activity, providing a reason for the app to stay alive, while other components take care of doing the "work". AsyncTasks do "work", but they will not, in and of themselves, keep a process alive.

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.

Categories

Resources