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

0

I'm developing a simple app with Android Studio and I need to create a timer to run some methods every 1 second.

I tried the following but it did not 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, a fatal error will occur closing the application.

    
asked by anonymous 31.05.2018 / 04:34

2 answers

2

I strongly recommend that you use the Handler class because on android, any process that is time-consuming and not on a thread will be considered a crash and will terminate with a critical error. Not sure, but as far as I know the Times class is not present on Android. Here's the best solution:

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 have put some code from the class so you can see where each line of code is. This works, any problem or question just ask!

    
31.05.2018 / 13:12
0
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
                }
            });
        }
    }
}
    
05.06.2018 / 07:03