android - Best way to perform an action periodically [while an app is running] - Handler? -


I am trying to take any action from time to time I say, sometimes 3 seconds after a class one I want to create a new instance. Would it be best to implement it using handler or thread? Is there an easy way, the way I can try? I'm not really good at using thread - I want to learn, but it is more important that I work before worrying about good programming practices.

  New thread () {Public Zero Run ()} / / ensures that the player still has 3 live (game == incorrect) {uiCallback.sendEmptyMessage (0); Try {Thread.Sleep (2000); // Wait two seconds before pulling next flower} Grip (Interrupted ejection) {// Tudo auto-generated catch block e.printStackTrace (); } // sleep for 2 seconds}}}. Start ();    

I am doing something similar in my Android app; I update some data in my interface every 10 seconds. There are several ways to do this, but I chose to use a handler because it is very easy to implement:

  thread timer = new thread () {public zero Run () {For (;;) {// Accessories in a separate thread uiCallback.sendEmptyMessage (0); Thread.Sleep (3000); // sleep for 3 seconds}}}); Timer.start (); ... private handler ui callback = new handler () {public works with null message messages (message messages) {/ UI}}};   

As you know, you can not run such periodic functions in the UI thread because it will block the UI. This creates a new thread that sends a message to the UI when it is done, you can update your UI with the new results of your periodic function.

If you do not need to update the UI with the results of this periodic function, then you can simply ignore the other end of your code example, and a new thread as shown. Be careful, however, if you are modifying the new threads and the UI shared volumes, then you are going to run into problems if you do not synchronize Generally, threading one There is no area where you want to ignore "good programming practices" because you will find strange, non-conformable errors and you will start pressing your program.

-tjw

Comments