Using Handler postDelayed to queue a task for later execution

I figured out how to get my android app to auto post after a certain amount of idle time.

 

Trick was to create a handler in the activity that is running.

 

Then make a “Runnable” function that will do what you want. — think of this as the “function to be run later”.

 

To call it later issues handler.postDelayed(runnable_function,20000);

 

If the user does something that makes you want to “reset” or cancel the pending call you can call handler.

private Handler handler = new Handler();

final Runnable post_score = new Runnable()
{
public void run()
{
Toast.makeText(getApplicationContext(), “Posting Score in Background.”, Toast.LENGTH_SHORT).show();
new PostScoreTask().execute(S);
}
};

 

// Queue up a message to Post this score
handler.removeCallbacks(post_score);
handler.postDelayed(post_score, auto_post_delay);

 

I call these two commands above any time the user changes something that should be posted to the server.  But each time they do something we cancel any pending posts and “Queue” up another message to ask that it be done after the specified auto_post_delay. ( which is an integer set to number of milliseconds to wait before posting.
This should cause the posting to be “near Real time” but not waste internet resources posting until current input has been completed.

 

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published.