[Android] implementation principle and enhanced version of switching from sub-thread to main thread at any time

Source: Internet
Author: User

[Android] implementation principle and enhanced version of switching from sub-thread to main thread at any time

 

InAndroidIn use, the user interface is often changed from the sub-thread to the main thread.Activity.HandlerThe problem can be solved. But what if there are many interfaces? Each interface createsHandler? Is it a waste? What we need is concise; what we need is efficiency! Start ....

It was originally intended to modify the implementation of the original article [Android] from the sub-thread to the main thread at any time. However, it could not be found. Some Problems in the original one made it difficult to edit, an editor is messy, but a new chapter is opened. I think it should be related to the many styles of code I copied.

In the previous chapter [Android], the implementation method of switching from the sub-thread to the main thread at any time is introduced. However, there is no system to talk about the principle. Here we will talk about it.

Principle Handler principle:

Of course, there are a lot of details that have not been drawn one by one. Here we will go first. Let's take a look. Haha.

ToolKit one-click operation principle:

It may be a little troublesome to look at here. You must first look at the content in the implementation of the previous chapter [Android] switching from the subthread to the main thread at any time and then look at it again. Otherwise, this image is a waste image.

New

They all said they want to add new features. What is it? There is a synchronization method as described in the previous chapter. This method will be returned only after the main thread executes the task of the subthread. This is a relatively reliable form.

If the sub-thread is a goddess, the main thread is you; now the Goddess is waiting for you to do things; but your popularity is quite good, there are many goddesses who give you the task; and one of them is not happy; she wants you to do it slowly, and I am still waiting for you, isn't it too easy to give you face.

Then the goddess thought, I will wait for you for half an hour. If you have done it for half an hour, I will accept you. If not, bye-bye.

For such a wait time, we need to add a new method:Public static void runOnMainThreadSync (Runnable runnable, int waitTime, boolean cancel).

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 create a new method, just a few changes above.

 

New public static void runOnMainThreadSync (Runnable runnable, int waitTime, boolean cancel ):

 

    public static void runOnMainThreadSync(Runnable runnable, int waitTime, boolean cancel) {        if (Looper.myLooper() == Looper.getMainLooper()) {            runnable.run();            return;        }        SyncPost poster = new SyncPost(runnable);        getMainPoster().sync(poster);        poster.waitRun(waitTime, cancel);    }
We can see two more parameters. One is the time for the goddess to wait: WaitTimeThe second parameter is that after the Goddess leaves, you have not done the task assigned by the goddess. (Cancel).

 

Goddess:Sub-thread Decoration
You:Main thread Decoration

Of course the correspondingSyncPostInPublic void waitRun ()You also need to add a similar method to the method. In order to explain the method, you can directly add the method without modifying it on 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 {                        this.wait(time);                    } catch (InterruptedException e) {                        e.printStackTrace();                    } finally {                        if (!end && cancel)                            end = true;                    }                }            }        }    }
You can see This. wait (time );Wait time.

 

At the same time, we changed the state of the END variable as needed. Of course, this is changed, so you need to judge the task first.

So the original execution method is: public void run ():

 

    public void run() {        synchronized (this) {            runnable.run();            end = true;            try {                this.notifyAll();            } catch (Exception e) {                e.printStackTrace();            }        }    }
To change:

 

 

    public void run() {        if(!end) {            synchronized (this) {                if(!end) {                    runnable.run();                    end = true;                    try {                        this.notifyAll();                    } catch (Exception e) {                        e.printStackTrace();                    }                }            }        }    }
That is, determine whether the status is Flase before and after synchronization. If yes, execution is required.

 

In the code sectionOKNow, you can test it!

Scenario

The features of the new addition are as follows: premise (the goddess tells you to do things; the maximum wait time is half an hour !)

 

Goddess is with you, then immediately do things. (In this case, the goddess is the main thread, and the actual work is the goddess; you can also be said; because you are also the main thread) the goddess waited for half an hour and then left, as for the task that you do not do after the goddess gave you, it depends on the attitude of the goddess. The Goddess has not started to do it before you wait. At this time, the goddess will not want to wait. That is to say, it will not execute this. wait (time); statement, because it exits after obtaining the synchronization block. The waiting time is spent waiting to enter the synchronization block. The Goddess has been waiting for 12 minutes. Now you have finished the task within 18 minutes. The Goddess has been waiting for 12 minutes. Now you have started to do it, but you still need 20 minutes to complete it. The goddess left before you finish it; at this time, no matter whether the goddess says you do it or not, you will finish it; you are a responsible man.

 

 

Summary

 

CancelVariables are effective only when the waiting time is reached but not yet executed. Once the task is started, it will not exit midway through, whether or not the Goddess has left.

 

Code:

ToolKit. java
HandlerPoster. java
SyncPost. java

 

Related Article

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.