Delay Execution of code

×

Error message

  • Warning: count(): Parameter must be an array or an object that implements Countable in bootstrap_table() (line 114 of /home/porquefu/public_html/android-snippets.com/sites/all/themes/bootstrap/templates/system/table.func.php).
  • Warning: count(): Parameter must be an array or an object that implements Countable in bootstrap_table() (line 189 of /home/porquefu/public_html/android-snippets.com/sites/all/themes/bootstrap/templates/system/table.func.php).
  • Warning: count(): Parameter must be an array or an object that implements Countable in bootstrap_table() (line 238 of /home/porquefu/public_html/android-snippets.com/sites/all/themes/bootstrap/templates/system/table.func.php).
  • Deprecated function: The each() function is deprecated. This message will be suppressed on further calls in menu_set_active_trail() (line 2405 of /home/porquefu/public_html/android-snippets.com/includes/menu.inc).
+1
-56
-1

Sometimes we need to delay the execution of a block of code, for example when retrying a failed operation.
here is how to do it:

XML code: 
JAVA code: 
//this code will print "this is the delayed code" debug log delayed by 10 seconds
 
Handler handler = new Handler(); //note, better use a member variable to avoid garbage collection
handler.postDelayed(new Runnable(){
@Override
      public void run(){
        Log.d("test","this is the delayed code"); //put here the code to be executed
   }
}
, 10000 //the delay time in milliseconds, in this example 10 seconds
 );