[Android] The implementation principle and the enhanced version of switching from a child thread to the main thread at any time

Source: Internet
Author: User

========================================================
Qiujuer
Blog:blog.csdn.net/qiujuer
website:www.qiujuer.net
Open Source Library: Genius-android
Reprint Please specify Source:http://blog.csdn.net/qiujuer/article/details/41900879
========================================================

In the use of Android often encountered from the sub-thread switch to the main thread to make the interface changes , if you are in one Activity to say a Handler can solve the problem But what if there are a lot of interfaces? Does each interface create a Handler ? It's a waste, isn't it? What we want is brevity, and efficiency! Walk up ....

Originally intended to be in the original article [Android] at any time from the sub-thread switch to the main thread of the implementation of the above to modify; but found not ah; the original one out of some problems lead to difficult to edit, an editor on the chaos of the sample, but a new chapter opened. I think it should be about a lot of code that I copied with style.

In the previous chapter [Android] at any time from the sub-thread switch to the main thread of the implementation of its implementation is described, but there is no system to say the principle;

principleHandler principle:


Of course, there are a lot of details of the part did not draw out, here is the first, will see AH haha.

ToolKit One-button operation principle:


It may be a bit of a hassle to look directly at it here. You must first see the previous chapter [Android] switch from a child thread to the contents of the main thread's implementation at any time. Otherwise the picture is a waste map.

New

Have said to join the new function, what is it? In the previous chapter, there is a synchronization method that will wait for the main thread to execute the child thread's task before the child thread returns. This is a form of comparative cheat.

If the child thread is the goddess, the main thread is you; now the Goddess is waiting for you to do something, but your popularity is good. There are many goddesses who have given you the task, and one of the goddesses is not happy; she thought that if you do it slowly, I still wait for you, I will not give you face.

Then the goddess thought, I wait for you half an hour, if half an hour you did then I will accept you, if not then goodbye.

For such time waits we need to add a new method: public static void Runonmainthreadsync (Runnable Runnable, int waitTime, Boolean cancel) .

The original Public static void Runonmainthreadsync (Runnable Runnable)

    public static void Runonmainthreadsync (Runnable Runnable) {        if (looper.mylooper () = = Looper.getmainlooper ()) {            Runnable.run ();            return;        }        Syncpost poster = new Syncpost (runnable);        Getmainposter (). sync (poster);        Poster.waitrun ();    }
Now we're going to create a new method, just a few changes.

New public static void Runonmainthreadsync (Runnable Runnable, int waitTime, Boolean cancel):

    public static void Runonmainthreadsync (Runnable Runnable, int waitTime, Boolean cancel) {        if (looper.mylooper () = = Loo Per.getmainlooper ()) {            runnable.run ();            return;        }        Syncpost poster = new Syncpost (runnable);        Getmainposter (). sync (poster);        Poster.waitrun (WaitTime, cancel);    }
you can see two more parameters, one is the time the goddess waits: waitTime ; The second parameter is whether you do not do the Goddess's task (cancel)after the goddess has gone.

Goddess: Sub-threaded trim
You: Main Thread Accessories

Of course the corresponding syncpost public void Waitrun () method also needs to add a similar method, in order to explain the method is added directly, did not modify the original method.

Original: public void Waitrun ():

    public void Waitrun () {        if (!end) {            synchronized (this) {                if (!end) {                    try {                        this.wait ();                    } catch ( Interruptedexception e) {                        e.printstacktrace ();}}}}    
Newly added: public void waitrun (int time, Boolean cancel):

    public void Waitrun (Int. time, Boolean cancel) {        if (!end) {            synchronized (this) {                if (!end) {                    try {                        th Is.wait (time);                    } catch (Interruptedexception e) {                        e.printstacktrace ();                    } finally {                        if (!end && cancel)                            end = true;}}}}    
You can see them. this.wait (time);Time to wait.

At the same time, we changed the state of the END variable according to the situation. Of course it changes here, so you need to judge when you do the task.

So the original execution method: public void Run ():

    public void Run () {        synchronized (this) {            runnable.run ();            end = true;            try {                this.notifyall ();            } catch (Exception e) {                e.printstacktrace ();}}    }
To change to:

    public void Run () {        if (!end) {            synchronized (this) {                if (!end) {                    runnable.run ();                    end = true;                    try {                        this.notifyall ();                    } catch (Exception e) {                        e.printstacktrace ();            }    }}}
which is enteringbefore and after synchronization, determine whether the state is flase . If so, then the execution will be executed.

The Code section is OK , you can test the test!

Scene

For the above new features have the following scenario: The premise (goddess told you to do things; the longest waiting time half an hour!) )

    • The Goddess is with you, so do it right away. (At this time the goddess is the main thread of the situation, the actual work is a goddess, it can be said that you, because you are the main thread)
    • The goddess waited for half an hour and then went away, as for the task that you did not do to the goddess, depending on the attitude of the goddess.
    • The Goddess has not waited for you to begin to do, at this time the goddess does not want to wait for the thing at all; Statement, because the synchronization block was fetched and exited. The time she waits is spent waiting to enter the sync block.
    • The Goddess has been waiting for 12 minutes, and when you start doing what you have done in 18 minutes, then it is time to finish the task.
    • The Goddess has been waiting for 12 minutes, and you begin to do it, but you need 20 minutes to complete, and the goddess is gone before you are done; you will do it when the goddess says you do it or not, and you are a responsible man.

Summarize

    • The cancel variable is effective only if the wait time is up to you but not yet executed.
    • Once a task has been executed, it will not exit halfway, whether or not the Goddess is gone.

Code:

Toolkit.java
Handlerposter.java
Syncpost.java


========================================================
Qiujuer
Blog: Blog.csdn.net/qiujuer
Website: www.qiujuer.net
Open Source Library: genius-android
Reprint Please specify source: http://blog.csdn.net/qiujuer/article/details/41900879
========================================================

[Android] The implementation principle and the enhanced version of switching from a child thread to the main thread at any time

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.