Android multithreading and services - java

I am little bit confused with multithreading in Android. I am aware we can achieve using AsyncTask and Handler. Generally when should we implement by extending Thread Class in Android? Can anyone give an example that we need to do it only by extending thread class but not with AsyncTask or Handler.
Consider a example app, we have a bouncing ball in an activity(forget the animation part), I need to change the color of the ball every 20 minutes, and I need to get the color code from the server and update the ball UI. Now how can I achieve this ? Can someone explain using AsyncTask or Handler and also only using Thread Class(without Asynctask or Handler)?
How should I handle downloading large payloads from server using services.

Thread
Long task in general
Invoke by thread.start() method
Triggered from any thread
Runs on its own thread
Manual thread management/code may become difficult to read
AsyncTask
Small task having to communicate with main thread
Invoke by execute() method
Triggered from main thread
Runs on worker thread
Must be executed and created from the main Thread
Service
Task with no UI,but should not use for long Task. Use Thread within service for long Task
Invoke by onStartService()
Triggered from any Thread
Runs On Main Thread
May block main(UI) thread
IntentService
Long task usually no communication with main thread if communication is needed then it is done by Handler or broadcast
Invoke via Intent
Triggered from Main Thread (Intent is received on main Thread and worker thread is spawned)
Runs on separate thread
Can't run task in parallel and multiple intents are Queued on the same worker thread.

Thread: Use it to separate long running computation from Main Thread ( UI Thread). If you don't need to update UI or send messages back to UI Thread, use it for long running tasks. But you don't really need to extend Thread and write your logic by overriding Thread methods. But still HandlerThread is effective compared to java Thread.
AsyncTask : it 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 milli seconds at the most). Recommended for 5 milli seconds task execution.
Service: Use it to handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
HandlerThread/Handler: A HandlerThread is effectively a long-running thread that grabs work from a queue, and operates on it. You can use it even to send results back to UI Thread via Handler of UI Thread.
Have a look at below posts for more details:
Asynctask vs Thread vs Services vs Loader
Handler vs AsyncTask vs Thread
Creating Background Service in Android
Android: Toast in a thread

An AsyncTask is basically a thread. It has 3 callBack methods(main) and the are executed in this order top to bottom:
1. onPreExecute()
2. doInBackground()
3. onPostExecute()
4. onProgressUpdate()
The onPreExecute() and onPostExecute() are running on the UI thread and doInBackground() is a separate thread as such. If you spawn a thread(not a AsyncTask), and try to set a property of a UI element from it, this will raise an exception saying: the original thread(the UI thread) which created the view can only modify it. So only the UI thread has these two properties:
Only it can add/modify the UI of the App
It cannot be blocked for more than 5 secs(ANR exception)
So to over come both these limitations in one go, we have AsyncTask, it can run resource consuming operations(network access, implementing gaming logic etc) in doInBackground(), and still provide ability to alter the UI from onPreExecute() and onPreExecute().

Related

Is Android AsyncTask use multithreading because android official web says?

while learning the difference between multi-threading and Concurrency.i follow this stackoverflow answer
according to my understanding AsyncTask is just used to on or off the use of main thread{ui thread} while events like http request or fetching data from database. and after task is done main thead is reallocated to the event by AsyncTask task.
but Android Official says "An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread"
now i am confused.
android use multi-theading its just wrapper class for thread management.
C# async and await is diffrent concept.
An AsyncTask "touches" two threads: Main/UI and the Background one. There are few of its methods that run on Main/UI Thread (onPre/onPostExecute()) and one method that is run on a WorkerThread in background. There is an internal sync/queue between those methods.
Concurrency (async/await) doesn't (necessarily) use a second thread but uses "moments of when the CPU is free". Think about this non-real case: if the Main/UI Thread is 100% busy then no any Concurrency could be executed until the Main/UIThread has a bit of "free CPU cycles" to share. Intead, in this last example AsyncTasks will do its job asynchronously without take in count other Threads (and its results will be queued to UI/MainThread to be processed later).

How to post callbacks in Android to any arbitrary thread

I am using the Unity game engine which also supports exporting to Android.
The engine uses multiple threads, including the UI thread and a separate scripting thread where all the user custom code is executing.
My scenario requires that i call some operation in a background thread, and i would like to marshal the result back to the main scripting thread.
I know the basics of the AsyncTask, Executor and Looper classes. Out of these, Looper seems like a good candidate since it allows setting up a queue and post back messages to a given thread (AsyncTask is "hardwired" to run the callback on the UI thread, which is not what i want here).
What is the proper way of achieving this?
There is 3 main ways to communicate with the UI thread :
Activity.runOnUiThread(Runnable)
View.post(Runnable)
Handlers
In your case, I advice you to create an Handler, as the 2 first solutions imply that you have a reference on your Activity or a View
Edit
If you want to use any thread in your app, just make sure a Looper has been set, and use an associated Handler
class YourLooperThread extends Thread
{
// make it accessible from the outside
private Handler handler;
#Override public void run()
{
Looper.prepare();
// Customize your handler, it has to be used in any thread which want to push a message in this thread's looper message Queue
handler = new Handler();
Looper.loop();
}
}
Be careful : all the other tasks you want to do in that thread must be done through the message queue, i.e posting a runnable in the handler. More information here : Handlers, MessageQueue, Looper, do they all run on the UI thread?

BlockingQueue on main Service thread

My android app has a long running background service, which I also understand runs in the application's main thread and for that reason, any time consuming or blocking task should be moved to a separate thread.
Now, here is the situation, I don't understand/confused about:
When I bind to the service from an activity, i receive an reference to the service which allows me to invoke service methods from my activity. One of the methods allows me to pass a String object from the activity to the service, which is then added to a BlockingQueue. A separate worker thread which is started in the Service's onCreate method, checks the queue for available data and then performs the required task.
What I want to understand is, if at some point, the queue becomes full and an attempt to the queue blocks, will it affect the main thread the service is running on?
Yes. In this situation, if the queue becomes full, the calling thread will block (in your situation, the main thread). So this is a bad design.
The produced data coming from a field of an Activity doesn't force you to use it on the main thread. I suggest you use some Handler for your producer running on its own thread which will allow you to make the processing (and eventually waiting on the queue) outside of the main thread.
This is also good for communicating with your Service since you can use Handlers to communicate with a Service (see Android Services' guide).
Finally, if applying the produced data can be passed directly to an Handler using either
Handler.post(Runnable) or Handler.send(Message)

AsyncTask, Handler, Thread... Which one to choose [duplicate]

This question already has answers here:
Handler vs AsyncTask vs Thread [closed]
(13 answers)
Closed 8 years ago.
I know this Question has been asked many times but all answers I got wasn't clear for Me.
I want to implement a File deletion process. I discovered that to do this kind of work it's recommended to run all the process in a separated thread.
For that, I can use AsyncTask, Handler and Thread. AsyncTask seems to be a good solution. However, AsyncTask is designed for small task. (When i try to delete a file whose length is more than 1G, AsyncTask crashes or doesn't execute onPostExecute.
Others thread handlers (Thread, Runnable...) can't manage UI (Update UI or show progress).
My Question is What is the good thread handler for Long tasks and How to manage UI with it.
First of all, if you need to perform work outside your main thread, but only while the user is interacting with your app, then you should create a new thread, otherwise use a Service.
Now, everything you can do with AsyncTask, you can also do it with a Thread(+ Handler). But the AsyncTask makes the developer job easier, because it is designed to communicate a worker thread with the main thread(caller thread). Now, if you use a Hanlder you can also communicate a worker thread with a caller thread(Note that the caller thread is not necessarily the main thread, it could be communication between two worker threads), if the caller thread is the main thread, you better use AsyncTask.
As far as i know, it goes something like this:
Use AsyncTask if you need to run a short task communicating with the UI thread
Use a Thread and Handler to run longer tasks that requires communication between the worker thread and the main thread(caller thread)
Use Thread, Handler and Looper (or HandlerThread, which is class for starting a thread that already has a Looper) for longer tasks that require communication between the worker thread and the caller thread(not the main thread).
Use IntentService for longer task that does not requires user interaction and needs only one worker thread.
The best for me, is the Asynctask, because the structure is well defined, you can know when is running the thread and when show the result.
http://masl.cis.gvsu.edu/2010/04/05/android-code-sample-asynchronous-http-connections/
Good article on using handlers above.
To delete using handler:
Create a runnable that does three things:
Delete file
Obtain msg and send on success
Obtain msg and send on failure
Using some framework to manage threads or using concurrency package, post the runnable and it will do the file Del off main thread. Handler callback will be msg success or msg fail that will process on main thread wherview controller.
Check out Needle and you can forget Handlers and AsyncTasks. Needle is an open-source, simple but powerful multithreading library for Android. With it you can say things like:
Needle.onMainThread().execute(new Runnable() {
#Override
public void run() {
// e.g. change one of the views
}
});
or
Needle.onBackgroundThread().execute(new UiRelatedTask<Integer>() {
#Override
protected Integer doWork() {
int result = 1+2;
return result;
}
#Override
protected void thenDoUiRelatedWork(Integer result) {
mSomeTextView.setText("result: " + result);
}
});
very simple API
fixed thread pool size
customizable thread pool size
supports UI interaction ("do work and then use result on UI thread")
android 1.5+
behaves the same on all platform versions
Check it out on GitHub: https://github.com/ZsoltSafrany/needle

What the UI thread will do if Activity/UI is idle for some(may be long) time

I think title itself says what the my question is...
AFAIK, in Java, when work of a Thread is completed i.e. run() method has completed executing, Thread itself will finish and dies.
So, When my Activity(I mean UI) is idle for a long time, what the UI thread will do? does it sleeps? or does it do any other work?
Thanks to all...
I believe the question is not really about Java threads in general, but about the Android "main thread" (also called the "UI thread").
To quote from the JavaDoc for the Android Handler:
When a process is created for your application, its main thread is
dedicated to running a message queue that takes care of managing the
top-level application objects (activities, broadcast receivers, etc)
and any windows they create. You can create your own threads, and
communicate back with the main application thread through a Handler.
This is done by calling the same post or sendMessage methods as
before, but from your new thread. The given Runnable or Message will
then be scheduled in the Handler's message queue and processed when
appropriate.
In other words: The main thread is responsible for dequeuing messages/runnables from a queue and processing them. That main thread is blocked while the queue is empty (since there is nothing for it to do). If you use a Handler that was created in the main thread, that Handler's messages and runnables will actually be added to the same queue used by the main thread. Normally, the main thread will run as long as the process does.
Note: An Android app can actually have multiple processes, and each one will have its own main thread. However, most Android apps will only have one process (and therefore one main thread).

Categories

Resources