1

The timer should work non stop once i start my program with one second interval. At the top of my MainActivity i added:

import java.util.Timer;

Then in the MainActivity class:

public class MainActivity extends ActionBarActivity

I added:

private Timer timer = new Timer();

Now i have the onCreate method:

@Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addListenerOnButton();
        currentActivity = this;
        initTTS();
    }

How can i make that the timer will start working once i'm starting my program with interval of a second ?

Shimrit Hadadi
  • 115
  • 1
  • 12

3 Answers3

3

First you need to import:

import java.util.Timer;
import java.util.TimerTask;

After this you need to setup your timer like this:

//Declare the timer
    Timer myTimer = new Timer();
    //Set the schedule function and rate
    myTimer.scheduleAtFixedRate(new TimerTask() {
                                    @Override
                                    public void run() {
                                        //Called at every 1000 milliseconds (1 second)
                                        Log.i("MainActivity", "Repeated task");
                                    }
                                },
            //set the amount of time in milliseconds before first execution
            0,
            //Set the amount of time between each execution (in milliseconds)
            1000);
Liviu
  • 768
  • 8
  • 9
1

You can start the timer with one of the schedule methods like this:

timer.schedule(new TimerTask() {
    @Override
    public void run() {
        //do your stuff here...
    }
}, 0, 1000);

This will start your timer with a delay of 0 milliseconds and repeat it after 1000 milliseconds.

You should read at least the heading of the javadoc here: java.util.Timer.

I don't know that much about the Android platform but you have to be cautious using threading. Read about this here: https://developer.android.com/guide/components/processes-and-threads.html#Threads

Mathias Begert
  • 2,354
  • 1
  • 16
  • 26
0

Set the interval to 1000, because the interval in timers are based on milliseconds, so 1000 milliseconds = 1 second.

try searching for the property "Interval" in the properties tab, because i use netbeans and there is interval on side, and the command to be put on the Timer_Tick event to make sure the command is done everytime the interval happens which is every second

  • But how do i set the interval ? Where and how do i start the timer in the onCreate ? And how do i make the tick event if there is any ? So far i used c# and timers but never in java. I'm using android studio 1.3. For example in c# you type timer.Interval = 1000; but in java i didn't see the property Interval for the variable timer. – Shimrit Hadadi Aug 26 '15 at 06:57