• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Beginner needing threads and handlers explaning

javano

Lurker
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:
package com.my.firstapp;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class firstapp extends Activity {
	
	Button start;
	Button stop;
	TextView duration;
	
	Integer intMillis;
	Integer intSeconds;
	Integer intMinutes;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        start= (Button)this.findViewById(R.id.start);
        stop= (Button)this.findViewById(R.id.stop);
        duration = (TextView)this.findViewById(R.id.txtDuration);
        
        start.setOnClickListener(new Button.OnClickListener() {public void onClick(View v) {start();} });
        stop.setOnClickListener(new Button.OnClickListener() {public void onClick(View v) {stop();} });
        
        intMillis= 0;
        intSeconds= 0;
        intMinutes= 0;
    }
    
    public void start() {
		//HERE I WANT TO START A NEW THREAD WHICH WILL DO SOMETHING EVERY 200ms 
		//UNTIL I PRESS THE STOP BUTTON
    }

    public voide stop() {
		//STOP THE 2ND THREAD
    }

}

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)?
 
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:
class MyTimerTask extends TimerTask
{
        //This method needs overridden
        @Override
        public void run
        {
              //Perform the task in this method
        }
}

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:
Timer timer = new Timer();
timer.schedule(new MyTimerTask(), 200);    //param1 = an instance of TimerTask, and
                                                           //param2 = number of ms to fire the event.

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:
//A new handler object to use as a negotiator between threads
Handler handler = new Handler(
{
    @Override
    public void handleMessage(Message m)
    {
         start.setText("Whatever");  //change the text on the start Button
    }
});

...
             
//The run method of your TimerTask subclass
public void run()
{
      handler.sendEmptyMessage(0);    //Send a generic message to the handler.
                                                   //Since you only have one message here, a generic
                                                   //message will suffice
}

...

If you still need help understanding something, let me know and I will try to elaborate.
 
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:
Timer timer = new Timer();
timer.schedule(new MyTimerTask(), 200)

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?
 
I am not sure I understand what you mean by your problem description.

Just declare a public static classwide variable like so:
Code:
public static Timer timer;

and then in your onCreate() function, initialize the variable:
Code:
public void onCreate(Bundle savedInstanceState)
{
            super.onCreate(savedInstanceState);
            timer =  new Timer();
            ...
            ...
}

Then in the onClick() method, depending on which button is clicked, make a call to either "timer.schedul(new MyTimerTask(), 200);" or "timer.cancel();".
 
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
 
Back
Top Bottom