Multithreading on Android
is to some extent an easy task due to the various possibilities available for us.
However it would be nice to understand the difference between the approaches.
What is the best way to multitask and based on what preferences is it the "best"?
AsyncTask
?class MultiTasker extends AsyncTask<, , >
Runnable
?Run开发者_如何学JAVAnable myRun = new Runnable(){ public void run(){ } }; Thread T = new Thread(myRun); T.start();
Handler
?class MultiTasker extends Handler
Asking which one is "best" is the wrong approach here - it depends on what you are trying to accomplish.
- Runnable/Thread - This is the basic, lowest-level ways to control threading in Java. Provided in the Java APIs, so they're not specific to Android. You can use these in Android programs, but you'll probably want to use one of the other two options for most tasks (or use them in addition to
Thread
s). - Handler - Provided in the Android APIs. You can
post()
aRunnable
directly, orsendMessage()
aMessage
(along with other options, such as providing a delay before processing aRunnable
orMessage
). However,Handler
isn't something you would use by itself to provide multithreading - it's use is usually to get back into the main activity (UI) thread. You'd start some otherThread
to do a process in the background, and inside of it wouldpost
aRunnable
using theHandler
when you needed to update the UI. Or if you had a task that didn't necessarily need to run in the background, but did need to pop up and do something every so often, you couldpost
aRunnable
with a delay to activate later, and then at the endpost
itself again with a delay. - AsyncTask - Provided in the Android APIs. This class is for doing something on a background thread, optionally providing incremental updates on the UI thread, and ultimately providing an end result on the UI thread. The
Params
,Progress
, andResult
generic types are used to provide start parameters, progress update data, and end result data, respectively. Internally,AsyncTask
usesThread
s,Runnable
s, andHandler
s to accomplish this task.
Its Always better if you go with AsyncTask()
.. because Thats something which has been built to solve MultiThreading
issues in Android..
精彩评论