How to set a timer in Android Studio to perform tasks at constant intervals?

I am developing a simple application with Android Studio and I need to create a timer to run some methods every 1 second.

I tried the following way but it didn't work:

int delay = 1000;
int interval = 1000;
Timer timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            // métodos ...
        }
    }, delay, interval);

When the timer is activated for the first time, fatal error occurs closing the application.

Author: ramaral, 2018-05-31

3 answers

I strongly recommend that you use the Class Handler because on android, any process that is a little time consuming and that is not in a Thread will be considered a crash and will be terminated with a critical error. Not sure, but as far as I know the Times class is not present on Android. The best solution follows:

import android.os.Bundle;
import android.os.Handler;

public class Nome_da_Classe extends AppCompatActivity implements Runnable{
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Handler handler = new Handler(); //contador de tempo
        handler.postDelayed(this, 1500); //o exemplo 2000 = 2 segundos

 }

@Override
    public void run() {

        //Esse métedo será execultado a cada período, ponha aqui a sua lógica 

    } 

}

Note that I put some class codes so you can observe where each line of code is. It works, any problem or doubt is just ask!

 2
Author: Edeson Bizerril, 2018-05-31 11:12:25
import java.util.Timer;
import java.util.TimerTask;

public class Main extends AppCompatActivity {

    public void Timer(){
        Timer timer = new Timer();
        Task task = new Task();

        timer.schedule(task, 1000, 1000);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Timer();
    }

    class Task extends TimerTask{

        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // Metodos
                }
            });
        }
    }
}
 1
Author: Gabriel Orlando, 2018-06-05 05:03:50

/ / let's go on the most important, the Timer class has a method called schedule, / / where this method receives the (TimerTask, long delay, long timesinmillis);

public void inicializaTimer() {

    this.mCalendarDateFirst.setTimeInMillis(mTime);

     this.mCalendarDateFirst.add(Calendar.HOUR, -1);

     String data = this.mCalendarDateFirst.getTime().toString();

    this.startaThread();

   this.mTimer.schedule(this.mTimerTask, mCalendarDateFirst.getTime(), 1000);
}



  public void startaThread() {

    this.mTimerTask = new TimerTask() {
        @Override
        public void run() {

/ / today on android using the timetask run and the handle O POST method. if you want to know more query in the android documentation "processes and chaining".

            mHandler.post(new Runnable() {
                @Override
                public void run() {

                    if (stop) {
                        mContext.stopService(new Intent(mContext, ServicoNotificacaoBackGround.class));
                    } else {
                        mCalendarAtual.setTimeInMillis(System.currentTimeMillis());
                        mCalendarHorario.setTimeInMillis(mTime);

                        Log.i("Data String", "Time " + mCalendarHorario.getTime().toString());
                        Log.i("Data String 2", "Time " + mCalendarAtual.getTime().toString());
                        if (mCalendarHorario.getTime().toString().equalsIgnoreCase(mCalendarAtual.getTime().toString())) {                   
                            stop = true;
                        }
                Toast.makeText(ExampleService.this, "Foi ! ", Toast.LENGTH_SHORT).show();
              Log.d("ExampleService", "Serviço Executando com Sucesso");

                    }
                }
            });
        }
    };         
}

This is an example that could be the solution to the problem, i.e. running every 1 second.

 0
Author: Miestrie, 2019-02-07 21:20:30