Monday, 1 February 2016

Handler vs AsyncTask vs runOnUiThread Handler vs Timer, Timer vs ScheduledExecutorService

if you don't have time, please just read all red content.




AsyncTask vs Handler



Summary:

When you are on the UI Thread and you want to call a web service, then use AsyncTask to do it.

When you are not on the UI Thread and you want to call UI Thread, then Handler suit for you.


http://stackoverflow.com/questions/6964011/handler-vs-asynctask-vs-thread


AsyncTask:
It's a simple way to use a thread without knowing anything about java thread modelAsyncTaskgives various callbacks respective to the worker thread and main thread.
Use for small waiting operations like the following:
  1. Fetching some data from web services and display over layout.
  2. Database query.
  3. When you realize that running operation will never, ever be nested.
Handler:
When we install an application in android then it create a thread for that application called MAIN UI Thread, All activities run inside that thread , By the android single thread model rule we can not access UI elements (bitmap , textview etc..) directly for another thread defined inside that activity.
A Handler allows you communicate back with the UI thread from other background thread. This is useful in android as android doesn’t allow other threads to communicate directly with UI thread. Handler can send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue. When a new Handler is created, it is bound to the thread/message queue of the thread that is creating it.
It's the best fit for:
  1. It allows you to do message queuing.
  2. Message scheduling.
Thread:
Now it's time to talk about thread.

Thread is the parent of both AsyncTask and Handler. They both internally use thread, which means you can also create your own thread model like AsyncTask and Handler, but that requires a good knowledge of Java's Multi-Threading Implementation.



1. Handler can send message.
2. Handler will run a task in the main thread (which means you can update ui directly)

http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html


AsyncTask gives you nice functions to override, "doInBackground" for the things you want to do out of main thread. "onPreExecute" and "onPostExecute", you can put your UI updating code here before your background code and after your background code.



Handler VS runOnUiThread



Summary

As I mentioned above if you are on an non ui thread, and you want to do something with UI, then Handler is the one you should use. But you may also heard about runOnUiThread, what is the different between handler and runOnUiThread?

Actually, runOnUiThread is using Handler to run your code. hence they are actually the same thing.





Activity.runOnUiThread() is a special case of more generic Handlers. With Handler you can create your own event query within your own thread. Using Handlers instantiated with default constructordoesn't mean "code will run on UI thread" in general. By default, handlers binded to Thread from which they was instantiated from.
To create Handler that is guaranteed to bind to UI (main) thread you should create Handlerobject binded to Main Looper like this:
Handler mHandler = new Handler(Looper.getMainLooper());
Moreover, if you check the implementation of runOnuiThread() method, it is using Handler to do the things:
  public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

As you can see from code snippet above, Runnable action will be executed immediately, if runOnUiThread() is called from the UI thread. Otherwise, it will post it to the Handler, which will be executed at some point later.




Timer vs ScheduledExecutorService

Answer: use ScheduledExecutorService

http://stackoverflow.com/questions/409932/java-timer-vs-executorservice
up vote177down voteaccepted
  • Timer can be sensitive to changes in the system clock, ScheduledThreadPoolExecutor isn't
  • Timer has only one execution thread, so long-running task can delay other tasks. ScheduledThreadPoolExecutor can be configured with any number of threads. Furthermore, you have full control over created threads, if you want (by providing ThreadFactory)
  • runtime exceptions thrown in TimerTask kill that one thread, thus making Timer dead :-( ... i.e. scheduled tasks will not run anymore. ScheduledThreadExecutor not only catches runtime exceptions, but it lets you handle them if you want (by overriding afterExecute method from ThreadPoolExecutor). Task which threw exception will be canceled, but other tasks will continue to run.
If you can use ScheduledThreadExecutor instead of Timer, do so.
One more thing... while ScheduledThreadExecutor isn't available in Java 1.4 library, there is aBackport of JSR 166 (java.util.concurrent) to Java 1.2, 1.3, 1.4, which has the ScheduledThreadExecutor class.
shareedit




If you change build an alert window in the thread you will not get any exception, but just failed


scheduledThreadPoolExecutor.scheduleAtFixedRate(new Runnable() {
    @Override    public void run() {
        don't do ui stuff there:

        
    }
},1, 3, TimeUnit.SECONDS);



if you want , you can :


runOnUiThread(new Runnable() {
    @Override    public void run() {
        AlertDialog.Builder builder = new AlertDialog.Builder(xx);
        builder.setMessage(R.string.picking_list_api_call_error_message).setTitle(R.string.error);
        builder.setCancelable(false);
        AlertDialog dialog = builder.create();
        dialog.show();
    }
});


After you shutdown a "scheduledThreadPoolExecutor.shutdown();" you can't call it agin, otherwise you will get this error:

rejected from java.util.concurrent.ScheduledThreadPoolExecutor
 .....






Loaders



。。。 i am  putting more things in .......
















No comments:

Post a comment