Search code examples
androidhandlerandroid-handlerandroid-runtime

Best practice for executing timed actions in Android


In a specific part of my code in need to run 3 actions in a a timed space, right now i am using this method:

Handler mHander = new Handler();


public void startChainActions(){

// do first action
      mHandler.postDelayed(new Runnable() {
          @Override
          public void run() {

          //do action 2

                    mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                    //do action 3
                    }
                  }
                }, 1500);

              }
             }
            }, 5000);
           }


public void cleanResources(){

    mHandler.removeCallbacksAndMessages(null);
    mHandler==null
}

When using this method i often see this message on my logcat:

W/art﹕ Suspending all threads took: 12.272ms

which leads me to believe it is slowing down performance. is there a better way to time actions after each other?


Solution

  • First of all you should understand that in case of Handlers you will execute Runnable in the same thread where handler was created. It means that you will share hardware power with any user<->UI interaction if you run it in a main thread, and there is no guarantee on exact time of execution start.

    Answering your question from body - no, there is no slowing down of performance because of 2 postDelayed calls, but could be because of your actions. So your log message is connected with something else.

    Update: Answering your question from title: if you'd like to run delayed action, than yes - it's a normal way to do it in Android, especially if you'd to run it in main/UI thread.