0

I am tasked with displaying a random number after a 5 second delay using Thread.sleep(5000), on a button click using the Handler/Looper/Thread/Runnable approach rather than implementing an AsyncTask. My problem is, I'm having issues finding examples online of how to implement this task with the aforementioned approach. So, following common HandlerThread/Looper related practices how would I implement this simple task that I described above?

As after thoughts (I mainly want to know about my question mentioned above right now):

  • I would like to make sure that multiple clicks of the Button don't restart the process with each click (only once the 5 seconds are up).
  • I would like to allow this simple task to be maintained throughout orientation changes, even if the orientation occurs midway through the 5 second delay that occurs via Thread.sleep(5000)

After, After thought:

  • The Button and TextView that display the random number exist within a fragment that my MainActivity calls.
  • Is there any particular thing steering you away from using an AsyncTask? Advantage of that is the onPostExecute function which is called on the Main thread for when its done allowing you to change the UI. – Mitch Dart Aug 11 '15 at 07:42
  • no need for `Thread`s, `AsyncTask`s, `Timer`s etc, just use `Handler#postDelayed`, that's all – pskink Aug 11 '15 at 07:44
  • Yea an AsyncTask would definitely be preferred for this sort of thing, but our professor asked us to practice the approach I outlined above as a means to study for the final I assume. It's to practice the scenario where we're loading data from the internet and the button is suppose to act like a "refresh" button – user3106433 Aug 11 '15 at 07:45
  • @pskink the necessity of the `Thread.sleep(5000)` is to simulate some task that will actually take up time. In the next phase of this practice assignment `Thread.sleep()` will be replaced by some task that actually takes time.. like downloading a picture for instance – user3106433 Aug 11 '15 at 07:56
  • so yes you can use `AsyncTask` or even better `IntentService` but the latter is a bit more complex... – pskink Aug 11 '15 at 07:59
  • Did you manage to do it or you still need an answer? – Andrei T Sep 22 '15 at 20:45
  • Yep, I got it done. Thanks very much though andrei – user3106433 Sep 23 '15 at 05:25

0 Answers0