I have the following task:
I have to do a Wi-Fi scan and then send some RSSs to the a server to obtain a location from the server. After that I should display the location on a map.
I have one activity in my application. What is the best way to implement it? I haven't implemented a thread nor AsyncTask in android before. So I don't know a lot about it. I have read about threads and AsyncTask on android developer website. But I still can't understand everything.
I would appreciate it if anyone can tell me when its the best to use threads, and how AsynTask is different from threads and when to use AsyncTask instead of threads.
EDIT: the task that I have to implement should run only when the user click on actioBar item
.
If you can't understand the read documentation, I'd suggest starting with an AsyncTask, as it already implements a Thread when doInBackground() is fired and it already implements some mechanisms that you would probably have to implement by hand when using Threads (concurrency, Thread start/stop processes, sending information to UI thread, ...).
However, you don't specify what exactly want to do. If you plan to do a long-running process, instead of Threads or AsyncTasks, it's recommended using Service that would start a Thread as implementation, as contrary to popular beliefs, AsyncTasks are meant for short-lasting tasks.
In any case, if you're starting with this, I'd recommend using AsyncTask first, and when understood what it's doing and how, decide by yourself what's the best way to implement what you're planning to do: if running a Service with a Thread inside, a Thread itself or an AsyncTask.
Related
I want to know which is better to download files, async task or service?
My app has eight buttons, which one starts one direfferent download (which download has ~10MB). When the user clicks on one button or more to download data is better to use async task or service?
Thanks!
In any case you should use AsyncTask because even service runs in the main (GUI) thread where no networking should be done. Whether to run the AsyncTask in a service or an activity depends on whether you want that download to continue in background.
all above answers have good points. but the life-cycle issue is the most important thing you should consider. for instance, let's say you use asyncTask. so the user starts downloading and suddenly he/she rotates the screen and because you tied the asyncTask life-cycle to activity another asyncTask operation will be kicked off and result in a compulsive 10mb download. so considering this you should use service and asyncTask together to maintain life-cycle issue and UI thread networking issue.
update: Intent-service is a better solution because it receives requests in its own thread and goes offline when it doesn't have anything to do
AsyncTask -- AsyncTask manipulate threads and/or handlers, if you can do that better with Looper and stuff why bother? AsyncTask is designed to be a helper class around Thread and Handler, and it should ideally be used for short operations (a few seconds at the most.).. how can you tell in production mode whether is not gonna take long? probably bad network, slow network,jammed network, phone restarting - and all these will probably make your downloading either corrupt or unfinished.. i am a user of apps, and i get pissed when i waste bundle on nothing..
if you ask me, use
Service
--Serviceis made to run irrespective of what app/screen is visible and make if communicate with the UI if only it is available if not continue with download and save it, AsyncTask does not constitute a generic threading framework. always use threads, its cool, we all love it.
When the user logs in into my app. I am starting an asynctask to maintain the user session. And that async task is running indefinitely till the user logs out. My problem is that when I try to start other asynctasks, their doInBackground() method is never executed.
I read somewhere that if an async task is already running, we cannot start new async task. I can confirm this because when i removed the user session async task, it worked properly. Is there a workaround?
P.S.: I have already used executeOnExecutor() method. but it didn't help.
For potentially long running operations I suggest you to use Service rather than asynctask.
Start the service when the user logs in
Intent i= new Intent(context, YourService.class);
i.putExtra("KEY1", "Value to be used by the service");
context.startService(i);
And stop the service when the user logs out
stopService(new Intent(this,YourService.class));
To get to know more about Service you can refer this
Service : Android developers
Service : Vogella
To know more about asynctask vs service you can refer this
Android: AsyncTask vs Service
When to use a Service or AsyncTask or Handler?
I read somewhere that if an async task is already running, we cannot start new async task.
Yes,That is fact that you can't run more then 5 (five) AsyncTaskat same time below the API 11 but for more yes you can using executeOnExecutor.
AsyncTask uses a thread pool pattern for running the stuff from doInBackground(). The issue is initially (in early Android OS versions) the pool size was just 1, meaning no parallel computations for a bunch of AsyncTasks. But later they fixed that and now the size is 5, so at most 5 AsyncTasks can run simultaneously.
I have figure out Some Threading rules and i found one major rule is below ,
The task can be executed only once (an exception will be thrown if a second execution is attempted.)
What is definition of AsyncTask?
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.
How & Where use it?
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended to use it.
Why you can't use multiple AsyncTask at same time ?
There are a few threading rules that must be followed for this class to work properly:
The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
The task instance must be created on the UI thread.
execute(Params...) must be invoked on the UI thread.
Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
The task can be executed only once (an exception will be thrown if a second execution is attempted.)
Running multiple AsyncTasks at the same time — not possible?
Test sample of parallel excution of AsyncTasks
Try Executor
You should go with Executor that will mange your multiple thread parallel.
Executor executor = anExecutor;
executor.execute(new RunnableTask1());
executor.execute(new RunnableTask2());
...
Sample Example 1
Sample Example 2
Just like a few others here, I object to the premise of the question.
Your core problem is that you are using an AsyncTask to perform a task beyond its scope. Others have noted this too. Those who offer solutions that can mitigate your problem through low-level threads (even java.util.Concurrent is low-level which is why Scala uses Akka actors as an abstraction), Service, etc. are quite clever, but they are treating the symptom rather than curing the disease.
As for what you should be doing, you are not the first to want to maintain a user session in an Android application. This is a solved problem. The common thread (no pun intended) in these solutions is the use of SharedPreferences. Here is a straightforward example of doing this. This Stack Overflow user combines SharedPreferences with OAuth to do something more sophisticated.
It is common in software development to solve problems by preventing them from happening in the first place. I think you can solve the problem of running simultaneous AsyncTasks by not running simultaneous AsyncTasks. User session management is simply not what an AsyncTask is for.
If you are developing for API 11 or higher, you can use AsyncTask.executeOnExecutor() allowing for multiple AsyncTasks to be run at once.
http://developer.android.com/reference/android/os/AsyncTask.html#executeOnExecutor(java.util.concurrent.Executor, Params...)
I'll share with you, what we do on our App.
To keep user Session (We use OAuth with access/refresh tokens), we create a Singleton in our Application extended class. Why we declare this Singleton inside the MainApplication class? (Thats the name of our class), because your Singleton's life will be tided to the Activity that has created it, so if your Application is running on low memory and Garbage Collector collects your paused Activities, it will release your Singleton instance because it's associated to that Activity.
Creating it inside your Application class will let it live inside your RAM as long as the user keeps using your app.
Then, to persists that session cross application uses, we save the credentials inside SharedPreferences encrypting the fields.
yes starting 2 or more asynctasks simultaneously may cause issues on some devices. i had experienced this issue few months back. i could not predict when the 2nd asyncTask would fail to run. The issue was intermittent may caused by usage of memory as i was executing ndk code in asynctask. but i remember well that it depended on memory of device.
Similar question had been asked before. I would post the link for the similar question.
AsyncTask.executeOnExecutor() before API Level 11
Some users suggest go for Service. My advice is don't go for that path yet. Using service is much more complicated. Even you are using service, you still have to deal with threading, as
Note that services, like other application objects, run in the main
thread of their hosting process. This means that, if your service is
going to do any CPU intensive (such as MP3 playback) or blocking (such
as networking) operations, it should spawn its own thread in which to
do that work....
If we can solve a problem in elegant way, don't go for the complicated way.
I would suggest that, try one of the APIs in java.util.concurrent as suggested in below
AsyncTask is designed to be a helper class around Thread and Handler
and does not constitute a generic threading framework. AsyncTasks
should ideally be used for short operations (a few seconds at the
most.) If you need to keep threads running for long periods of time,
it is highly recommended you use the various APIs provided by the
java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and
FutureTask.
I can't give you any code example so far, as I do not know how you design your session managing mechanism.
If you think your long running session managing task shouldn't bind to the life cycle of your main application life cycle, then only you might want to consider Service. However, bear in mind that, communication among your main application and Service is much more cumbersome and complicated.
For more details, please refer to http://developer.android.com/guide/components/services.html, under section Should you use a service or a thread?
I'm building an Android library to collect data from the host app and send this data to an online server in the background. I realize that this would require some sort of multi-threading/use of a service/forking.
The application simply keeps adding data through library calls, and the library should handle the sending of this data in the background without disturbing the main UI.
How should I got about making this library? Should the entire library run on an Android Service? Should I just use another thread? This is my first foray into parallelism. I'm not sure what the best way to do this is.
A detailed response is appreciated.
Some of the answers aren't quite correct. Services (Android Service component) are NOT made to run in the background, they run in the default UI thread.
In all honesty, the question shouldn't be service or thread or anything. Your library does NOT need to kick start a service, it could simply be a class (singleton/static, whatever it is) that should extend AsyncTask (or anything else running in the background that I'll explain in a bit) and use the doInBackground method to send stuff to the server. Note AsyncTask is nothing but a Thread internally. So here's what I would do:
Let's call your library's main class that interfaces with your server ServerHelper. You can make this a singleton (or static but that's a separate discussion). Within this class create an innerclass say ServerHelperCommandTask and extend AsyncTask. You really should review AsyncTask in detail to understand how that works. Because you would be asked to override doInBackGround. Anything you put in this method will autmoatically get exectued in a separate thread off the UI. Then a callback is invoked called onPostExecute that you can override as you will get the result from doInBackground here. This OnPostExecute is called in the mainThread so you can check for say error results here, etc etc.
This would be the simplest method; however, there are many other methods and libraries that help you with networking and deal with all the background stuff internally. Google just release a library called Volley which you may be able to plugin and use as it would do all the parallel processing for you. But that may take a bit of learning curve. Hope you understand AsyncTasks as in your case if the data pushed isn't a lot, then AsyncTasks is the way to go. Also note that you can call multiple AsyncTasks but while that seems on the surface that it is kicking off multiple parallel threads, that isn't quite accurate since honeycomb as internally you can call 5 Asynctasks but all 5 of those tasks will be executed sequentially so you wouldn't have to worry much about serializing.
Service would be a more reliable solution for situation You described.
I mean running background threads from service, not from Activity. Service itself does not provide separate thread by default, by the way.
The point is that Services have higher priority than acitivities so they will be destroyed with less probabilty, so your long-running task won't be interrupted.
You could do both but here's pros and cons for each solution :
Services are made to run in the background, even when your app is not in the foreground. sers usually don't like having services running for nothing.
From your description it seems that you would only need to have this thread running when the app is in foreground right ?
If so, a normal thread could do the job.
However, a service might be easier to implement.
Hope it helps
You should definitely use a Service in this situation. Async tasks and manually creating a thread is not really suitable for computations that need to run in the background for network communication. Use the Async task for long running local computations (e.g. for an algorithm doing sorting).
Note that if you use a service, it will by nature NOT run as a background thread! You need to handle threading manually. In order to save yourself from this hassle (especially if it is your first time with multi-threading) use an IntentService!
The IntentService may be invoked using the startService method as with any other service, but the IntentService class is able to handle multiple invocations as in a producer/consumer pattern. This means that you can queue commands automatically to the service just using the startService method. In the IntentService class that you make, you can then handle different types of commands by looking at the given action inside of the intent that is sent along as a parameter in the startService method.
Here is an example of how the implementation of an IntentService:
public class SimpleIntentService extends IntentService {
public SimpleIntentService() {
super("SimpleIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
String commnad = intent.getAction();
//handle your command here and execute your desired code depending on this command
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Handler vs AsyncTask vs Thread
Am a newbie to android and am on the way developing my first app...
Which kind of threading is better to create process separate from UI thread?
AsyncTask or extending Thread class with Handler and Message?
I have gone throug this thread..
Put an object in Handler message
The person have told that, "Oh, and I'm moving away from using AsyncTask objects, as I believe they increase code coupling too much.".
What's meant by code coupling? Should I use Java thread with Handler and Message classes or should I use Async task?
As this is going to be your first app it would be best to put this question away for a while. Instead you would want to make your application working anyhow. Doing that you will gain enough experience to decide for yourself.
Having said this AsyncTask seems to be easier to use if what you need is to do something in background and present progress and results in UI.
One real problem with either approach is that when you rotate your device your UI gets recreated. And if you store ane references to the older UI in your thread/asynctask and use them your app the crashes.
AsyncTask uses Java's native threads in the background. The advantage of using them is that you get 3 methods - onPreExecute, doInBackground & onPostExecute which make you life easier.
AsyncTask is a nice abstraction for well-defined tasks that need to be done on a worker thread (to avoid blocking the main thread), while reporting progress and publishing results to the UI. Examples of such tasks are : downloading file from internet, calling a webservice, querying the database etc. It maintains a pool a worker threads to run these tasks. Using AsyncTask frees you from having to write code to create and mange threads and to dispatch UI updates to the UI thread.
AsyncTask is not appropriate when the background task is an ongoing process rather than a well-defined task. Examples : playing music, continuously tracking location, continuously downloading news feeds etc. In such cases, it is appropriate to create and manage a separate thread.
I am new to android development. Currently i am working on an application which will take a query from user, send the query to the server and will receive an XML response in return. Then it will process the xML response using XMLparser, will extract the answer from XML response and display answer to the user. Since all this processing takes some time, i want to show a progress dialog to the user for the processing time it takes.
I have gone through some ways of doing this like i can use AsyncTask, Handler or Runnable (java) threads. But as much I have read about all these, I have got confused which one to use.
Please tell me which one is better to use for above mentioned scenario. And a simple way to implement the preferred one.
Thank You in advance.
I'd recommend you to use AsyncTask because it is simplier than other approaches and it suits your needs.
I think you mess a bit these three different entities:
AsyncTask runs a set of actions in a separate thread, can show progress during its work and show notification when the task is completed.
Runnable is a command that can be performed. You should run in a separate thread. Also you should develop a logic in this case how to update progress and how to notify when the task is finished.
Handler is a special class that can handle messages that are sent to the handler's thread.
From http://developer.android.com/reference/android/os/AsyncTask.html :
This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask is designed for a use very similar to yours.
Runnable is only to run a block of code on another thread:
Represents a command that can be executed. Often used to run code in a different Thread.
(http://developer.android.com/reference/java/lang/Runnable.html)
Handler is used more for Message Queuing. Your case doesn't seem to require messages being sent repeatedly.
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
http://developer.android.com/reference/android/os/Handler.html
Note that neither Runnable nor Handler talk about displaying the results back on the UI thread. That is where AsyncTask helps you more than either of these.
It may be my personal preference - but I would use AsyncTask in your case. It provides all necessary controls for starting up the task, updating progress as necessary, etc. I have a very similar requirement in my app (send request to server, get response in XML, parse response, do something with the data) - I'm using AsyncTasks for this purpose.
As far I know AsyncTask is the recommended way. I think is the easiest way to implement and the more "Android best practice" for asynchronous tasks.
Could you refer to this question
Here's how I see it.
Handler is more for queuing many actions, and gives a bit more control. It's better for repetitive tasks which are generally not restricted to the UI.
AsyncTask provides a simple way to do background processing, not caring much about the lower-level stuff. It's great for relatively small, individual UI updates.
IMO, you should use AsyncTask. That being said, it's kind of a toss-up.
I think it's a matter of self-preference, but in your case I would go for the AsyncTask because it facilitates the interaction between the UI thread and the background thread.
I'd use a combination of AsyncTask and Handler, because please remember that you cannot change the UI from outside the UI thread (in this case you cannot intervene and show the answer to the user).
To overcome this, I ran the AsyncTask and catched the result with a custom callback method, which simply encapsulate it inside a Message and sends it to my custom Handler, which is inside the UI thread and can safely render on-screen my result.
AsyncTask might be the choice,because it provides all necessary controls for starting up the async task, updating progress bar, etc.
But, the point is AsyncTask is the best solution to the scenario.
Handler or Runnable are more suitable to duplex cases, like chat apps.