Do you have a problem using 2 Handler.postDelay() at the same time?

Asked

Viewed 213 times

2

I wonder if there is a problem with the App’s performance in using 2 handler.postDlay() at the same time, type calling the 2 in functions: inside the Oncreate Td1(); Td2();

public void Td1(){

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {

        @Override
        public void run() {



            handler.postDelayed(this, 5 * 1000);
        }
    }, 5 * 1000);

}

public void Td2(){

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {

        @Override
        public void run() {



            handler.postDelayed(this, 5 * 1000);
        }
    }, 5 * 1000);

}

1 answer

3


It will depend on what methods run() do.

Remember that the method run() will be executed in thread where the Handler, in this case at Uithread.

Also bear in mind that arguments being passed to postDelay equal and the methods Td1() and Td2() called one after the other, it’s practically the same as having only one postDelay to execute the content of each of the methods run(), one after the other.

Suppose that tasks 1 and 2 are scheduled, one in each postDelay:

public void Td1(){

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {

        @Override
        public void run() {

            tarefa_1();
            handler.postDelayed(this, 5 * 1000);
        }
    }, 5 * 1000);

}

public void Td2(){

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {

        @Override
        public void run() {

            tarefa_2();
            handler.postDelayed(this, 5 * 1000);
        }
    }, 5 * 1000);

}

call for Td1(); and then Td2(); is the same as having only one method(Td3) that schedules the two tasks:

public void Td3(){

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {

        @Override
        public void run() {

            tarefa_1();
            tarefa_2();
            handler.postDelayed(this, 5 * 1000);
        }
    }, 5 * 1000);

}

and call only Td3();

  • then in case I should wear everything on a single tread?

  • Don’t confuse thread with Handler.

  • right, but in that case, I could put all the actions within one, I can use divided into 2, that’s my doubt!

  • You can put in one or two, what I tried to explain is whether calling the Td1 and Td2 methods one after the other is the same as calling one with all actions.

  • I get it, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.