Beginner needing threads and handlers explaning


Last Updated:

  1. javano

    javano New Member This Topic's Starter

    Joined:
    Nov 5, 2010
    Messages:
    4
    Likes Received:
    0
    Ok, I have been reading an writing as I go along but I have gotten myself into a complete mess. My short code is below, I need help filling in the gaps. The problem is that just looking at the Google documentation simply details properties and methods of classes, functions, objects etc but doesn't (IMO) clearly explain them. How can I tackle the code below?

    Code (Text):
    1.  
    2. package com.my.firstapp;
    3.  
    4. import android.app.Activity;
    5. import android.os.Bundle;
    6. import android.view.View;
    7. import android.widget.Button;
    8. import android.widget.EditText;
    9.  
    10. public class firstapp extends Activity {
    11.    
    12.     Button start;
    13.     Button stop;
    14.     TextView duration;
    15.    
    16.     Integer intMillis;
    17.     Integer intSeconds;
    18.     Integer intMinutes;
    19.    
    20.     /** Called when the activity is first created. */
    21.     @Override
    22.     public void onCreate(Bundle savedInstanceState) {
    23.         super.onCreate(savedInstanceState);
    24.         setContentView(R.layout.main);
    25.        
    26.         start= (Button)this.findViewById(R.id.start);
    27.         stop= (Button)this.findViewById(R.id.stop);
    28.         duration = (TextView)this.findViewById(R.id.txtDuration);
    29.        
    30.         start.setOnClickListener(new Button.OnClickListener() {public void onClick(View v) {start();} });
    31.         stop.setOnClickListener(new Button.OnClickListener() {public void onClick(View v) {stop();} });
    32.        
    33.         intMillis= 0;
    34.         intSeconds= 0;
    35.         intMinutes= 0;
    36.     }
    37.    
    38.     public void start() {
    39.         //HERE I WANT TO START A NEW THREAD WHICH WILL DO SOMETHING EVERY 200ms
    40.         //UNTIL I PRESS THE STOP BUTTON
    41.     }
    42.  
    43.     public voide stop() {
    44.         //STOP THE 2ND THREAD
    45.     }
    46.  
    47. }
    48.  
    I have been Google'ing my behind off, and I have read so many different tutorials about threads, clocks, handlers, I've lost my self, can someone explain how to do this (and if possible why they have made the suggestion they did)?
     

    Advertisement
  2. jonbonazza

    jonbonazza Well-Known Member

    Joined:
    Jul 13, 2010
    Messages:
    1,934
    Likes Received:
    458
    Ok, so basically, since you are wanting to do something every 20 seconds, you won't want to use a generic Thread object, you will want to use what is called a TimerTask (which is a subclass of Thread). What you want to do is create a subclass of TimerTask like so:

    Code (Text):
    1.  
    2. class MyTimerTask extends TimerTask
    3. {
    4.         //This method needs overridden
    5.         @Override
    6.         public void run
    7.         {
    8.               //Perform the task in this method
    9.         }
    10. }
    11.  
    Then you will want to create an instance of a Timer object and initialize it in your onCreate Method and schedule a timer event like this:

    Code (Text):
    1.  
    2. Timer timer = new Timer();
    3. timer.schedule(new MyTimerTask(), 200);    //param1 = an instance of TimerTask, and
    4.                                                            //param2 = number of ms to fire the event.
    5.  
    Just keep in mind that you cannot do anything to the UI directly in the run() method of a thread (this also applies to TimerTask and any other subclass of Thread). This is where handlers come into play.

    For example, to change the text on a button, you would need the following

    Code (Text):
    1.  
    2.  
    3. //A new handler object to use as a negotiator between threads
    4. Handler handler = new Handler(
    5. {
    6.     @Override
    7.     public void handleMessage(Message m)
    8.     {
    9.          start.setText("Whatever");  //change the text on the start Button
    10.     }
    11. });
    12.  
    13. ...
    14.              
    15. //The run method of your TimerTask subclass
    16. public void run()
    17. {
    18.       handler.sendEmptyMessage(0);    //Send a generic message to the handler.
    19.                                                    //Since you only have one message here, a generic
    20.                                                    //message will suffice
    21. }
    22.  
    23. ...
    24.  
    25.  
    If you still need help understanding something, let me know and I will try to elaborate.
     
  3. javano

    javano New Member This Topic's Starter

    Joined:
    Nov 5, 2010
    Messages:
    4
    Likes Received:
    0
    Hi jonbonazza,

    Thanks very much that has cleared things up nicely! :D I have implemented your suggestion and its work just great. I have one more question I would like to ask though;

    I have used your exampled provided and placed the following code on a start button:
    Code (Text):
    1.  
    2. Timer timer = new Timer();
    3. timer.schedule(new MyTimerTask(), 200)
    4.  
    To implement a stop button with "timer.cancel();", the "Timer timer = new Timer();" line must be moved out of start buttons function into my activity class because the stop button can't resolved the Timer when its within the start button function.

    The problem is after pressing top and using timer.cancel() I need to create the timer again before it can be used again (before I can click start again). How can I when pressing start declare a timer that is public reachable from anywhere in the code?
     
  4. jonbonazza

    jonbonazza Well-Known Member

    Joined:
    Jul 13, 2010
    Messages:
    1,934
    Likes Received:
    458
    I am not sure I understand what you mean by your problem description.

    Just declare a public static classwide variable like so:
    Code (Text):
    1.  
    2. public static Timer timer;
    3.  
    and then in your onCreate() function, initialize the variable:
    Code (Text):
    1.  
    2. public void onCreate(Bundle savedInstanceState)
    3. {
    4.             super.onCreate(savedInstanceState);
    5.             timer =  new Timer();
    6.             ...
    7.             ...
    8. }
    9.  
    Then in the onClick() method, depending on which button is clicked, make a call to either "timer.schedul(new MyTimerTask(), 200);" or "timer.cancel();".
     
  5. javano

    javano New Member This Topic's Starter

    Joined:
    Nov 5, 2010
    Messages:
    4
    Likes Received:
    0
    Hi jonbonazza,

    Thanks for your reply. I actually managed to work it out for my self in the end and that is exactly what I did :D
     

Share This Page

Loading...