What exactly does the post method do?











up vote
84
down vote

favorite
45












I've encountered a very weird feature.



When I'm trying to run an animation on the main thread, it does not start.
When I run said animation using



getView().post(new Runnable() {
@Override
public void run() {
getView().startAnimation(a);
}
});


It does start.



I've printed the CurrentThread before starting the animation and both print main.



Obviously, I am missing something here, as both should start the animation on the main thread...
My guess is that as post adds the task to the queue, it starts at a more "correct time", but I would love to know what happens here at more depth.



EDIT:
Let me clear things up - my question is, why starting the animation on post causes it to start, when starting the animation on the main thread does not.










share|improve this question
























  • Is this behavior specific to an Android version? I could not reproduce it on Android 4.1.2!
    – Akdeniz
    Dec 12 '12 at 21:40










  • I reproduced this behavior on Android 2.3.3. But for AnimationDrawable! Ordinary Animation instance started to animate successfully on each setup. In AnimationDrawable case; when you try to start it in onCreate, it dont start because of not being attached to view at that moment. So it is not a threading issue for AnimationDrawable. Maybe same thing applies for Animation? developer.android.com/guide/topics/graphics/…
    – Akdeniz
    Dec 12 '12 at 22:59















up vote
84
down vote

favorite
45












I've encountered a very weird feature.



When I'm trying to run an animation on the main thread, it does not start.
When I run said animation using



getView().post(new Runnable() {
@Override
public void run() {
getView().startAnimation(a);
}
});


It does start.



I've printed the CurrentThread before starting the animation and both print main.



Obviously, I am missing something here, as both should start the animation on the main thread...
My guess is that as post adds the task to the queue, it starts at a more "correct time", but I would love to know what happens here at more depth.



EDIT:
Let me clear things up - my question is, why starting the animation on post causes it to start, when starting the animation on the main thread does not.










share|improve this question
























  • Is this behavior specific to an Android version? I could not reproduce it on Android 4.1.2!
    – Akdeniz
    Dec 12 '12 at 21:40










  • I reproduced this behavior on Android 2.3.3. But for AnimationDrawable! Ordinary Animation instance started to animate successfully on each setup. In AnimationDrawable case; when you try to start it in onCreate, it dont start because of not being attached to view at that moment. So it is not a threading issue for AnimationDrawable. Maybe same thing applies for Animation? developer.android.com/guide/topics/graphics/…
    – Akdeniz
    Dec 12 '12 at 22:59













up vote
84
down vote

favorite
45









up vote
84
down vote

favorite
45






45





I've encountered a very weird feature.



When I'm trying to run an animation on the main thread, it does not start.
When I run said animation using



getView().post(new Runnable() {
@Override
public void run() {
getView().startAnimation(a);
}
});


It does start.



I've printed the CurrentThread before starting the animation and both print main.



Obviously, I am missing something here, as both should start the animation on the main thread...
My guess is that as post adds the task to the queue, it starts at a more "correct time", but I would love to know what happens here at more depth.



EDIT:
Let me clear things up - my question is, why starting the animation on post causes it to start, when starting the animation on the main thread does not.










share|improve this question















I've encountered a very weird feature.



When I'm trying to run an animation on the main thread, it does not start.
When I run said animation using



getView().post(new Runnable() {
@Override
public void run() {
getView().startAnimation(a);
}
});


It does start.



I've printed the CurrentThread before starting the animation and both print main.



Obviously, I am missing something here, as both should start the animation on the main thread...
My guess is that as post adds the task to the queue, it starts at a more "correct time", but I would love to know what happens here at more depth.



EDIT:
Let me clear things up - my question is, why starting the animation on post causes it to start, when starting the animation on the main thread does not.







android






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 6 '16 at 7:50









Cactus

18.6k847110




18.6k847110










asked Dec 12 '12 at 12:39









Gal

2,56242142




2,56242142












  • Is this behavior specific to an Android version? I could not reproduce it on Android 4.1.2!
    – Akdeniz
    Dec 12 '12 at 21:40










  • I reproduced this behavior on Android 2.3.3. But for AnimationDrawable! Ordinary Animation instance started to animate successfully on each setup. In AnimationDrawable case; when you try to start it in onCreate, it dont start because of not being attached to view at that moment. So it is not a threading issue for AnimationDrawable. Maybe same thing applies for Animation? developer.android.com/guide/topics/graphics/…
    – Akdeniz
    Dec 12 '12 at 22:59


















  • Is this behavior specific to an Android version? I could not reproduce it on Android 4.1.2!
    – Akdeniz
    Dec 12 '12 at 21:40










  • I reproduced this behavior on Android 2.3.3. But for AnimationDrawable! Ordinary Animation instance started to animate successfully on each setup. In AnimationDrawable case; when you try to start it in onCreate, it dont start because of not being attached to view at that moment. So it is not a threading issue for AnimationDrawable. Maybe same thing applies for Animation? developer.android.com/guide/topics/graphics/…
    – Akdeniz
    Dec 12 '12 at 22:59
















Is this behavior specific to an Android version? I could not reproduce it on Android 4.1.2!
– Akdeniz
Dec 12 '12 at 21:40




Is this behavior specific to an Android version? I could not reproduce it on Android 4.1.2!
– Akdeniz
Dec 12 '12 at 21:40












I reproduced this behavior on Android 2.3.3. But for AnimationDrawable! Ordinary Animation instance started to animate successfully on each setup. In AnimationDrawable case; when you try to start it in onCreate, it dont start because of not being attached to view at that moment. So it is not a threading issue for AnimationDrawable. Maybe same thing applies for Animation? developer.android.com/guide/topics/graphics/…
– Akdeniz
Dec 12 '12 at 22:59




I reproduced this behavior on Android 2.3.3. But for AnimationDrawable! Ordinary Animation instance started to animate successfully on each setup. In AnimationDrawable case; when you try to start it in onCreate, it dont start because of not being attached to view at that moment. So it is not a threading issue for AnimationDrawable. Maybe same thing applies for Animation? developer.android.com/guide/topics/graphics/…
– Akdeniz
Dec 12 '12 at 22:59












4 Answers
4






active

oldest

votes

















up vote
138
down vote













post :post causes the Runnable to be added to the message queue,



Runnable : Represents a command that can be executed. Often used to run code in a different Thread.



run () : Starts executing the active part of the class' code. This method is called when a thread is started that has been created with a class which implements Runnable.



getView().post(new Runnable() {

@Override
public void run() {
getView().startAnimation(a);
}
});


code : getView().startAnimation(a);



in your code,



post causes the Runnable (the code will be run a in different thread) to add the message queue.



So startAnimation will be fired in a new thread when it is fetched from the messageQueue



[EDIT 1]



Why do we use a new thread instead of UI thread (main thread)?



UI Thread :




  • When application is started, Ui Thread is created automatically


  • it is in charge of dispatching the events to the appropriate widgets
    and this includes the drawing events.


  • It is also the thread you interact with Android widgets with




For instance, if you touch the a button on screen, the UI thread
dispatches the touch event to the widget which in turn sets its
pressed state and posts an invalidate request to the event queue. The
UI thread dequeues the request and notifies the widget to redraw
itself.




What happens if a user press a button which will do longOperation ?



((Button)findViewById(R.id.Button1)).setOnClickListener(           
new OnClickListener() {
@Override
public void onClick(View v) {
final Bitmap b = loadImageFromNetwork();
mImageView.setImageBitmap(b);
}
});


The UI freezes. The program may even crash.



public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
final Bitmap b = loadImageFromNetwork();
mImageView.setImageBitmap(b);
}
}).start();
}


It breaks the android rule that never update UI directly from worker thread



Android offers several ways to access the UI thread from other threads.




  • Activity.runOnUiThread(Runnable)

  • View.post(Runnable)

  • View.postDelayed(Runnable, long)

  • Handler


Like below,



View.post(Runnable)



public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
final Bitmap b = loadImageFromNetwork();
mImageView.post(new Runnable() {
public void run() {
mImageView.setImageBitmap(b);
}
});
}
}).start();
}


Handler



final Handler myHandler = new Handler();

(new Thread(new Runnable() {

@Override
public void run() {
final Bitmap b = loadImageFromNetwork();
myHandler.post(new Runnable() {

@Override
public void run() {
mImageView.setImageBitmap(b);
}
});
}
})).start();
}


enter image description here



For more info



http://android-developers.blogspot.com/2009/05/painless-threading.html



http://www.aviyehuda.com/blog/2010/12/20/android-multithreading-in-a-ui-environment/






share|improve this answer



















  • 11




    So why does starting the animation on post is different than running it on the main thread, when they both eventually run on the same thread?
    – Gal
    Dec 12 '12 at 13:18










  • Because this single thread model can yield poor performance in Android applications.
    – Talha
    Dec 12 '12 at 13:36










  • What does poor performance has to do with not showing an animation?
    – Gal
    Dec 12 '12 at 13:59










  • Dont think this only about startanimation. It means, " dont do it in UIThread, do it in new thread. "
    – Talha
    Dec 12 '12 at 14:28






  • 11




    I don't think this answers the question, this is more like a generic answer for beginners who doesn't know anything about the ui-thread and multi threading. This doesn't explains why throwing the animation ahead in the queue makes the animation work; an animation is supposed to be something to execute directly in the ui-thread without using any post() or runOnUiThread() tricks.
    – carrizo
    Nov 15 '16 at 5:45


















up vote
19
down vote













Is this being done on onCreate or onCreateView? If so, the app might not be in a state where the View is attached to the window. A lot of algorithms based on View metrics may not work since things like the View's measurements and position may have not been calculated. Android animations typically require them to run through UI math



View.post actually queues the animation on the View's message loop, so once the view gets attached to the window, it executes the animation instead of having it execute manually.



You are actually running things on the UI thread, but at a different time






share|improve this answer




























    up vote
    15
    down vote













    Have a look here for a good answer. view.post() is the same as handler.post() pretty much. It goes into the main thread queue and gets executed after the other pending tasks are finished. If you call activity.runOnUiThread() it will be called immediately on the UI thread.






    share|improve this answer



















    • 26




      One massive (and extremely helpful) difference I've found is the runnable in view.post() will be called when the View is first shown. I.E., you can set it to start an animation upon inflation of the View then at some point in the future, finally add it to the view hierarchy. At which point, then animation will execute and you won't have to worry about it.
      – DeeV
      Dec 12 '12 at 12:52


















    up vote
    3
    down vote













    The problem I think could be the life-cycle method where you are calling the post() method. Are you doing it in onCreate()? if so look at what I found in the activity's onResume() documentation:




    onResume()



    Added in API level 1 void onResume () Called after
    onRestoreInstanceState(Bundle), onRestart(), or onPause(), for your
    activity to start interacting with the user. This is a good place to
    begin animations
    , open exclusive-access devices (such as the
    camera), etc.




    https://developer.android.com/reference/android/app/Activity.html#onResume()



    So, as Joe Plante said, maybe the view is not ready to start animations at the moment you call post(), so try moving it to onResume().



    PD: Actually if you do move the code to onResume() then I think you can remove the post() call since you are already in the ui-thread and the view should be ready to start animations.






    share|improve this answer

















    • 2




      onResume may be called multiple times (screens goes to sleep, activity pushed to backstack, etc...) after it is initially when "the view is ready". If called from onResume, then a flag may be needed to track weather the animation has already been started, to avoid (re)starting multiple times.
      – sam.is
      Oct 4 '17 at 13:36













    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f13840007%2fwhat-exactly-does-the-post-method-do%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    138
    down vote













    post :post causes the Runnable to be added to the message queue,



    Runnable : Represents a command that can be executed. Often used to run code in a different Thread.



    run () : Starts executing the active part of the class' code. This method is called when a thread is started that has been created with a class which implements Runnable.



    getView().post(new Runnable() {

    @Override
    public void run() {
    getView().startAnimation(a);
    }
    });


    code : getView().startAnimation(a);



    in your code,



    post causes the Runnable (the code will be run a in different thread) to add the message queue.



    So startAnimation will be fired in a new thread when it is fetched from the messageQueue



    [EDIT 1]



    Why do we use a new thread instead of UI thread (main thread)?



    UI Thread :




    • When application is started, Ui Thread is created automatically


    • it is in charge of dispatching the events to the appropriate widgets
      and this includes the drawing events.


    • It is also the thread you interact with Android widgets with




    For instance, if you touch the a button on screen, the UI thread
    dispatches the touch event to the widget which in turn sets its
    pressed state and posts an invalidate request to the event queue. The
    UI thread dequeues the request and notifies the widget to redraw
    itself.




    What happens if a user press a button which will do longOperation ?



    ((Button)findViewById(R.id.Button1)).setOnClickListener(           
    new OnClickListener() {
    @Override
    public void onClick(View v) {
    final Bitmap b = loadImageFromNetwork();
    mImageView.setImageBitmap(b);
    }
    });


    The UI freezes. The program may even crash.



    public void onClick(View v) {
    new Thread(new Runnable() {
    public void run() {
    final Bitmap b = loadImageFromNetwork();
    mImageView.setImageBitmap(b);
    }
    }).start();
    }


    It breaks the android rule that never update UI directly from worker thread



    Android offers several ways to access the UI thread from other threads.




    • Activity.runOnUiThread(Runnable)

    • View.post(Runnable)

    • View.postDelayed(Runnable, long)

    • Handler


    Like below,



    View.post(Runnable)



    public void onClick(View v) {
    new Thread(new Runnable() {
    public void run() {
    final Bitmap b = loadImageFromNetwork();
    mImageView.post(new Runnable() {
    public void run() {
    mImageView.setImageBitmap(b);
    }
    });
    }
    }).start();
    }


    Handler



    final Handler myHandler = new Handler();

    (new Thread(new Runnable() {

    @Override
    public void run() {
    final Bitmap b = loadImageFromNetwork();
    myHandler.post(new Runnable() {

    @Override
    public void run() {
    mImageView.setImageBitmap(b);
    }
    });
    }
    })).start();
    }


    enter image description here



    For more info



    http://android-developers.blogspot.com/2009/05/painless-threading.html



    http://www.aviyehuda.com/blog/2010/12/20/android-multithreading-in-a-ui-environment/






    share|improve this answer



















    • 11




      So why does starting the animation on post is different than running it on the main thread, when they both eventually run on the same thread?
      – Gal
      Dec 12 '12 at 13:18










    • Because this single thread model can yield poor performance in Android applications.
      – Talha
      Dec 12 '12 at 13:36










    • What does poor performance has to do with not showing an animation?
      – Gal
      Dec 12 '12 at 13:59










    • Dont think this only about startanimation. It means, " dont do it in UIThread, do it in new thread. "
      – Talha
      Dec 12 '12 at 14:28






    • 11




      I don't think this answers the question, this is more like a generic answer for beginners who doesn't know anything about the ui-thread and multi threading. This doesn't explains why throwing the animation ahead in the queue makes the animation work; an animation is supposed to be something to execute directly in the ui-thread without using any post() or runOnUiThread() tricks.
      – carrizo
      Nov 15 '16 at 5:45















    up vote
    138
    down vote













    post :post causes the Runnable to be added to the message queue,



    Runnable : Represents a command that can be executed. Often used to run code in a different Thread.



    run () : Starts executing the active part of the class' code. This method is called when a thread is started that has been created with a class which implements Runnable.



    getView().post(new Runnable() {

    @Override
    public void run() {
    getView().startAnimation(a);
    }
    });


    code : getView().startAnimation(a);



    in your code,



    post causes the Runnable (the code will be run a in different thread) to add the message queue.



    So startAnimation will be fired in a new thread when it is fetched from the messageQueue



    [EDIT 1]



    Why do we use a new thread instead of UI thread (main thread)?



    UI Thread :




    • When application is started, Ui Thread is created automatically


    • it is in charge of dispatching the events to the appropriate widgets
      and this includes the drawing events.


    • It is also the thread you interact with Android widgets with




    For instance, if you touch the a button on screen, the UI thread
    dispatches the touch event to the widget which in turn sets its
    pressed state and posts an invalidate request to the event queue. The
    UI thread dequeues the request and notifies the widget to redraw
    itself.




    What happens if a user press a button which will do longOperation ?



    ((Button)findViewById(R.id.Button1)).setOnClickListener(           
    new OnClickListener() {
    @Override
    public void onClick(View v) {
    final Bitmap b = loadImageFromNetwork();
    mImageView.setImageBitmap(b);
    }
    });


    The UI freezes. The program may even crash.



    public void onClick(View v) {
    new Thread(new Runnable() {
    public void run() {
    final Bitmap b = loadImageFromNetwork();
    mImageView.setImageBitmap(b);
    }
    }).start();
    }


    It breaks the android rule that never update UI directly from worker thread



    Android offers several ways to access the UI thread from other threads.




    • Activity.runOnUiThread(Runnable)

    • View.post(Runnable)

    • View.postDelayed(Runnable, long)

    • Handler


    Like below,



    View.post(Runnable)



    public void onClick(View v) {
    new Thread(new Runnable() {
    public void run() {
    final Bitmap b = loadImageFromNetwork();
    mImageView.post(new Runnable() {
    public void run() {
    mImageView.setImageBitmap(b);
    }
    });
    }
    }).start();
    }


    Handler



    final Handler myHandler = new Handler();

    (new Thread(new Runnable() {

    @Override
    public void run() {
    final Bitmap b = loadImageFromNetwork();
    myHandler.post(new Runnable() {

    @Override
    public void run() {
    mImageView.setImageBitmap(b);
    }
    });
    }
    })).start();
    }


    enter image description here



    For more info



    http://android-developers.blogspot.com/2009/05/painless-threading.html



    http://www.aviyehuda.com/blog/2010/12/20/android-multithreading-in-a-ui-environment/






    share|improve this answer



















    • 11




      So why does starting the animation on post is different than running it on the main thread, when they both eventually run on the same thread?
      – Gal
      Dec 12 '12 at 13:18










    • Because this single thread model can yield poor performance in Android applications.
      – Talha
      Dec 12 '12 at 13:36










    • What does poor performance has to do with not showing an animation?
      – Gal
      Dec 12 '12 at 13:59










    • Dont think this only about startanimation. It means, " dont do it in UIThread, do it in new thread. "
      – Talha
      Dec 12 '12 at 14:28






    • 11




      I don't think this answers the question, this is more like a generic answer for beginners who doesn't know anything about the ui-thread and multi threading. This doesn't explains why throwing the animation ahead in the queue makes the animation work; an animation is supposed to be something to execute directly in the ui-thread without using any post() or runOnUiThread() tricks.
      – carrizo
      Nov 15 '16 at 5:45













    up vote
    138
    down vote










    up vote
    138
    down vote









    post :post causes the Runnable to be added to the message queue,



    Runnable : Represents a command that can be executed. Often used to run code in a different Thread.



    run () : Starts executing the active part of the class' code. This method is called when a thread is started that has been created with a class which implements Runnable.



    getView().post(new Runnable() {

    @Override
    public void run() {
    getView().startAnimation(a);
    }
    });


    code : getView().startAnimation(a);



    in your code,



    post causes the Runnable (the code will be run a in different thread) to add the message queue.



    So startAnimation will be fired in a new thread when it is fetched from the messageQueue



    [EDIT 1]



    Why do we use a new thread instead of UI thread (main thread)?



    UI Thread :




    • When application is started, Ui Thread is created automatically


    • it is in charge of dispatching the events to the appropriate widgets
      and this includes the drawing events.


    • It is also the thread you interact with Android widgets with




    For instance, if you touch the a button on screen, the UI thread
    dispatches the touch event to the widget which in turn sets its
    pressed state and posts an invalidate request to the event queue. The
    UI thread dequeues the request and notifies the widget to redraw
    itself.




    What happens if a user press a button which will do longOperation ?



    ((Button)findViewById(R.id.Button1)).setOnClickListener(           
    new OnClickListener() {
    @Override
    public void onClick(View v) {
    final Bitmap b = loadImageFromNetwork();
    mImageView.setImageBitmap(b);
    }
    });


    The UI freezes. The program may even crash.



    public void onClick(View v) {
    new Thread(new Runnable() {
    public void run() {
    final Bitmap b = loadImageFromNetwork();
    mImageView.setImageBitmap(b);
    }
    }).start();
    }


    It breaks the android rule that never update UI directly from worker thread



    Android offers several ways to access the UI thread from other threads.




    • Activity.runOnUiThread(Runnable)

    • View.post(Runnable)

    • View.postDelayed(Runnable, long)

    • Handler


    Like below,



    View.post(Runnable)



    public void onClick(View v) {
    new Thread(new Runnable() {
    public void run() {
    final Bitmap b = loadImageFromNetwork();
    mImageView.post(new Runnable() {
    public void run() {
    mImageView.setImageBitmap(b);
    }
    });
    }
    }).start();
    }


    Handler



    final Handler myHandler = new Handler();

    (new Thread(new Runnable() {

    @Override
    public void run() {
    final Bitmap b = loadImageFromNetwork();
    myHandler.post(new Runnable() {

    @Override
    public void run() {
    mImageView.setImageBitmap(b);
    }
    });
    }
    })).start();
    }


    enter image description here



    For more info



    http://android-developers.blogspot.com/2009/05/painless-threading.html



    http://www.aviyehuda.com/blog/2010/12/20/android-multithreading-in-a-ui-environment/






    share|improve this answer














    post :post causes the Runnable to be added to the message queue,



    Runnable : Represents a command that can be executed. Often used to run code in a different Thread.



    run () : Starts executing the active part of the class' code. This method is called when a thread is started that has been created with a class which implements Runnable.



    getView().post(new Runnable() {

    @Override
    public void run() {
    getView().startAnimation(a);
    }
    });


    code : getView().startAnimation(a);



    in your code,



    post causes the Runnable (the code will be run a in different thread) to add the message queue.



    So startAnimation will be fired in a new thread when it is fetched from the messageQueue



    [EDIT 1]



    Why do we use a new thread instead of UI thread (main thread)?



    UI Thread :




    • When application is started, Ui Thread is created automatically


    • it is in charge of dispatching the events to the appropriate widgets
      and this includes the drawing events.


    • It is also the thread you interact with Android widgets with




    For instance, if you touch the a button on screen, the UI thread
    dispatches the touch event to the widget which in turn sets its
    pressed state and posts an invalidate request to the event queue. The
    UI thread dequeues the request and notifies the widget to redraw
    itself.




    What happens if a user press a button which will do longOperation ?



    ((Button)findViewById(R.id.Button1)).setOnClickListener(           
    new OnClickListener() {
    @Override
    public void onClick(View v) {
    final Bitmap b = loadImageFromNetwork();
    mImageView.setImageBitmap(b);
    }
    });


    The UI freezes. The program may even crash.



    public void onClick(View v) {
    new Thread(new Runnable() {
    public void run() {
    final Bitmap b = loadImageFromNetwork();
    mImageView.setImageBitmap(b);
    }
    }).start();
    }


    It breaks the android rule that never update UI directly from worker thread



    Android offers several ways to access the UI thread from other threads.




    • Activity.runOnUiThread(Runnable)

    • View.post(Runnable)

    • View.postDelayed(Runnable, long)

    • Handler


    Like below,



    View.post(Runnable)



    public void onClick(View v) {
    new Thread(new Runnable() {
    public void run() {
    final Bitmap b = loadImageFromNetwork();
    mImageView.post(new Runnable() {
    public void run() {
    mImageView.setImageBitmap(b);
    }
    });
    }
    }).start();
    }


    Handler



    final Handler myHandler = new Handler();

    (new Thread(new Runnable() {

    @Override
    public void run() {
    final Bitmap b = loadImageFromNetwork();
    myHandler.post(new Runnable() {

    @Override
    public void run() {
    mImageView.setImageBitmap(b);
    }
    });
    }
    })).start();
    }


    enter image description here



    For more info



    http://android-developers.blogspot.com/2009/05/painless-threading.html



    http://www.aviyehuda.com/blog/2010/12/20/android-multithreading-in-a-ui-environment/







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 11 at 20:52









    Charlie

    5812826




    5812826










    answered Dec 12 '12 at 12:56









    Talha

    10.5k44158




    10.5k44158








    • 11




      So why does starting the animation on post is different than running it on the main thread, when they both eventually run on the same thread?
      – Gal
      Dec 12 '12 at 13:18










    • Because this single thread model can yield poor performance in Android applications.
      – Talha
      Dec 12 '12 at 13:36










    • What does poor performance has to do with not showing an animation?
      – Gal
      Dec 12 '12 at 13:59










    • Dont think this only about startanimation. It means, " dont do it in UIThread, do it in new thread. "
      – Talha
      Dec 12 '12 at 14:28






    • 11




      I don't think this answers the question, this is more like a generic answer for beginners who doesn't know anything about the ui-thread and multi threading. This doesn't explains why throwing the animation ahead in the queue makes the animation work; an animation is supposed to be something to execute directly in the ui-thread without using any post() or runOnUiThread() tricks.
      – carrizo
      Nov 15 '16 at 5:45














    • 11




      So why does starting the animation on post is different than running it on the main thread, when they both eventually run on the same thread?
      – Gal
      Dec 12 '12 at 13:18










    • Because this single thread model can yield poor performance in Android applications.
      – Talha
      Dec 12 '12 at 13:36










    • What does poor performance has to do with not showing an animation?
      – Gal
      Dec 12 '12 at 13:59










    • Dont think this only about startanimation. It means, " dont do it in UIThread, do it in new thread. "
      – Talha
      Dec 12 '12 at 14:28






    • 11




      I don't think this answers the question, this is more like a generic answer for beginners who doesn't know anything about the ui-thread and multi threading. This doesn't explains why throwing the animation ahead in the queue makes the animation work; an animation is supposed to be something to execute directly in the ui-thread without using any post() or runOnUiThread() tricks.
      – carrizo
      Nov 15 '16 at 5:45








    11




    11




    So why does starting the animation on post is different than running it on the main thread, when they both eventually run on the same thread?
    – Gal
    Dec 12 '12 at 13:18




    So why does starting the animation on post is different than running it on the main thread, when they both eventually run on the same thread?
    – Gal
    Dec 12 '12 at 13:18












    Because this single thread model can yield poor performance in Android applications.
    – Talha
    Dec 12 '12 at 13:36




    Because this single thread model can yield poor performance in Android applications.
    – Talha
    Dec 12 '12 at 13:36












    What does poor performance has to do with not showing an animation?
    – Gal
    Dec 12 '12 at 13:59




    What does poor performance has to do with not showing an animation?
    – Gal
    Dec 12 '12 at 13:59












    Dont think this only about startanimation. It means, " dont do it in UIThread, do it in new thread. "
    – Talha
    Dec 12 '12 at 14:28




    Dont think this only about startanimation. It means, " dont do it in UIThread, do it in new thread. "
    – Talha
    Dec 12 '12 at 14:28




    11




    11




    I don't think this answers the question, this is more like a generic answer for beginners who doesn't know anything about the ui-thread and multi threading. This doesn't explains why throwing the animation ahead in the queue makes the animation work; an animation is supposed to be something to execute directly in the ui-thread without using any post() or runOnUiThread() tricks.
    – carrizo
    Nov 15 '16 at 5:45




    I don't think this answers the question, this is more like a generic answer for beginners who doesn't know anything about the ui-thread and multi threading. This doesn't explains why throwing the animation ahead in the queue makes the animation work; an animation is supposed to be something to execute directly in the ui-thread without using any post() or runOnUiThread() tricks.
    – carrizo
    Nov 15 '16 at 5:45












    up vote
    19
    down vote













    Is this being done on onCreate or onCreateView? If so, the app might not be in a state where the View is attached to the window. A lot of algorithms based on View metrics may not work since things like the View's measurements and position may have not been calculated. Android animations typically require them to run through UI math



    View.post actually queues the animation on the View's message loop, so once the view gets attached to the window, it executes the animation instead of having it execute manually.



    You are actually running things on the UI thread, but at a different time






    share|improve this answer

























      up vote
      19
      down vote













      Is this being done on onCreate or onCreateView? If so, the app might not be in a state where the View is attached to the window. A lot of algorithms based on View metrics may not work since things like the View's measurements and position may have not been calculated. Android animations typically require them to run through UI math



      View.post actually queues the animation on the View's message loop, so once the view gets attached to the window, it executes the animation instead of having it execute manually.



      You are actually running things on the UI thread, but at a different time






      share|improve this answer























        up vote
        19
        down vote










        up vote
        19
        down vote









        Is this being done on onCreate or onCreateView? If so, the app might not be in a state where the View is attached to the window. A lot of algorithms based on View metrics may not work since things like the View's measurements and position may have not been calculated. Android animations typically require them to run through UI math



        View.post actually queues the animation on the View's message loop, so once the view gets attached to the window, it executes the animation instead of having it execute manually.



        You are actually running things on the UI thread, but at a different time






        share|improve this answer












        Is this being done on onCreate or onCreateView? If so, the app might not be in a state where the View is attached to the window. A lot of algorithms based on View metrics may not work since things like the View's measurements and position may have not been calculated. Android animations typically require them to run through UI math



        View.post actually queues the animation on the View's message loop, so once the view gets attached to the window, it executes the animation instead of having it execute manually.



        You are actually running things on the UI thread, but at a different time







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Oct 22 '14 at 15:54









        Joe Plante

        5,36222422




        5,36222422






















            up vote
            15
            down vote













            Have a look here for a good answer. view.post() is the same as handler.post() pretty much. It goes into the main thread queue and gets executed after the other pending tasks are finished. If you call activity.runOnUiThread() it will be called immediately on the UI thread.






            share|improve this answer



















            • 26




              One massive (and extremely helpful) difference I've found is the runnable in view.post() will be called when the View is first shown. I.E., you can set it to start an animation upon inflation of the View then at some point in the future, finally add it to the view hierarchy. At which point, then animation will execute and you won't have to worry about it.
              – DeeV
              Dec 12 '12 at 12:52















            up vote
            15
            down vote













            Have a look here for a good answer. view.post() is the same as handler.post() pretty much. It goes into the main thread queue and gets executed after the other pending tasks are finished. If you call activity.runOnUiThread() it will be called immediately on the UI thread.






            share|improve this answer



















            • 26




              One massive (and extremely helpful) difference I've found is the runnable in view.post() will be called when the View is first shown. I.E., you can set it to start an animation upon inflation of the View then at some point in the future, finally add it to the view hierarchy. At which point, then animation will execute and you won't have to worry about it.
              – DeeV
              Dec 12 '12 at 12:52













            up vote
            15
            down vote










            up vote
            15
            down vote









            Have a look here for a good answer. view.post() is the same as handler.post() pretty much. It goes into the main thread queue and gets executed after the other pending tasks are finished. If you call activity.runOnUiThread() it will be called immediately on the UI thread.






            share|improve this answer














            Have a look here for a good answer. view.post() is the same as handler.post() pretty much. It goes into the main thread queue and gets executed after the other pending tasks are finished. If you call activity.runOnUiThread() it will be called immediately on the UI thread.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 23 '17 at 11:33









            Community

            11




            11










            answered Dec 12 '12 at 12:47









            Tas Morf

            2,755188




            2,755188








            • 26




              One massive (and extremely helpful) difference I've found is the runnable in view.post() will be called when the View is first shown. I.E., you can set it to start an animation upon inflation of the View then at some point in the future, finally add it to the view hierarchy. At which point, then animation will execute and you won't have to worry about it.
              – DeeV
              Dec 12 '12 at 12:52














            • 26




              One massive (and extremely helpful) difference I've found is the runnable in view.post() will be called when the View is first shown. I.E., you can set it to start an animation upon inflation of the View then at some point in the future, finally add it to the view hierarchy. At which point, then animation will execute and you won't have to worry about it.
              – DeeV
              Dec 12 '12 at 12:52








            26




            26




            One massive (and extremely helpful) difference I've found is the runnable in view.post() will be called when the View is first shown. I.E., you can set it to start an animation upon inflation of the View then at some point in the future, finally add it to the view hierarchy. At which point, then animation will execute and you won't have to worry about it.
            – DeeV
            Dec 12 '12 at 12:52




            One massive (and extremely helpful) difference I've found is the runnable in view.post() will be called when the View is first shown. I.E., you can set it to start an animation upon inflation of the View then at some point in the future, finally add it to the view hierarchy. At which point, then animation will execute and you won't have to worry about it.
            – DeeV
            Dec 12 '12 at 12:52










            up vote
            3
            down vote













            The problem I think could be the life-cycle method where you are calling the post() method. Are you doing it in onCreate()? if so look at what I found in the activity's onResume() documentation:




            onResume()



            Added in API level 1 void onResume () Called after
            onRestoreInstanceState(Bundle), onRestart(), or onPause(), for your
            activity to start interacting with the user. This is a good place to
            begin animations
            , open exclusive-access devices (such as the
            camera), etc.




            https://developer.android.com/reference/android/app/Activity.html#onResume()



            So, as Joe Plante said, maybe the view is not ready to start animations at the moment you call post(), so try moving it to onResume().



            PD: Actually if you do move the code to onResume() then I think you can remove the post() call since you are already in the ui-thread and the view should be ready to start animations.






            share|improve this answer

















            • 2




              onResume may be called multiple times (screens goes to sleep, activity pushed to backstack, etc...) after it is initially when "the view is ready". If called from onResume, then a flag may be needed to track weather the animation has already been started, to avoid (re)starting multiple times.
              – sam.is
              Oct 4 '17 at 13:36

















            up vote
            3
            down vote













            The problem I think could be the life-cycle method where you are calling the post() method. Are you doing it in onCreate()? if so look at what I found in the activity's onResume() documentation:




            onResume()



            Added in API level 1 void onResume () Called after
            onRestoreInstanceState(Bundle), onRestart(), or onPause(), for your
            activity to start interacting with the user. This is a good place to
            begin animations
            , open exclusive-access devices (such as the
            camera), etc.




            https://developer.android.com/reference/android/app/Activity.html#onResume()



            So, as Joe Plante said, maybe the view is not ready to start animations at the moment you call post(), so try moving it to onResume().



            PD: Actually if you do move the code to onResume() then I think you can remove the post() call since you are already in the ui-thread and the view should be ready to start animations.






            share|improve this answer

















            • 2




              onResume may be called multiple times (screens goes to sleep, activity pushed to backstack, etc...) after it is initially when "the view is ready". If called from onResume, then a flag may be needed to track weather the animation has already been started, to avoid (re)starting multiple times.
              – sam.is
              Oct 4 '17 at 13:36















            up vote
            3
            down vote










            up vote
            3
            down vote









            The problem I think could be the life-cycle method where you are calling the post() method. Are you doing it in onCreate()? if so look at what I found in the activity's onResume() documentation:




            onResume()



            Added in API level 1 void onResume () Called after
            onRestoreInstanceState(Bundle), onRestart(), or onPause(), for your
            activity to start interacting with the user. This is a good place to
            begin animations
            , open exclusive-access devices (such as the
            camera), etc.




            https://developer.android.com/reference/android/app/Activity.html#onResume()



            So, as Joe Plante said, maybe the view is not ready to start animations at the moment you call post(), so try moving it to onResume().



            PD: Actually if you do move the code to onResume() then I think you can remove the post() call since you are already in the ui-thread and the view should be ready to start animations.






            share|improve this answer












            The problem I think could be the life-cycle method where you are calling the post() method. Are you doing it in onCreate()? if so look at what I found in the activity's onResume() documentation:




            onResume()



            Added in API level 1 void onResume () Called after
            onRestoreInstanceState(Bundle), onRestart(), or onPause(), for your
            activity to start interacting with the user. This is a good place to
            begin animations
            , open exclusive-access devices (such as the
            camera), etc.




            https://developer.android.com/reference/android/app/Activity.html#onResume()



            So, as Joe Plante said, maybe the view is not ready to start animations at the moment you call post(), so try moving it to onResume().



            PD: Actually if you do move the code to onResume() then I think you can remove the post() call since you are already in the ui-thread and the view should be ready to start animations.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 15 '16 at 6:09









            carrizo

            437310




            437310








            • 2




              onResume may be called multiple times (screens goes to sleep, activity pushed to backstack, etc...) after it is initially when "the view is ready". If called from onResume, then a flag may be needed to track weather the animation has already been started, to avoid (re)starting multiple times.
              – sam.is
              Oct 4 '17 at 13:36
















            • 2




              onResume may be called multiple times (screens goes to sleep, activity pushed to backstack, etc...) after it is initially when "the view is ready". If called from onResume, then a flag may be needed to track weather the animation has already been started, to avoid (re)starting multiple times.
              – sam.is
              Oct 4 '17 at 13:36










            2




            2




            onResume may be called multiple times (screens goes to sleep, activity pushed to backstack, etc...) after it is initially when "the view is ready". If called from onResume, then a flag may be needed to track weather the animation has already been started, to avoid (re)starting multiple times.
            – sam.is
            Oct 4 '17 at 13:36






            onResume may be called multiple times (screens goes to sleep, activity pushed to backstack, etc...) after it is initially when "the view is ready". If called from onResume, then a flag may be needed to track weather the animation has already been started, to avoid (re)starting multiple times.
            – sam.is
            Oct 4 '17 at 13:36




















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f13840007%2fwhat-exactly-does-the-post-method-do%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Bressuire

            Vorschmack

            Quarantine