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

Asked

Viewed 5,196 times

1

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

I tried it this 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 first activated, fatal error occurs by closing the application.

  • What error does it make? What code is running within the method run().

3 answers

2


I strongly recommend using the class Handler because on android, any process a little time-consuming and that is not in a Thread will be considered a lock and will be terminated with a critical error. I’m not sure, but as far as I know the Times class is not present on Android. Follows 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 put some code in the class so you can see where each line of code is. This works, any problem or doubt just ask!

  • 1

    Using Handler I can get an action executed after a certain time. But it’s not repeating itself as well as I need

  • No, mate, Handler will repeat every period indefinitely, that is, until you stop him. I use all the time on Android and that’s exactly how it works.

1

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
                }
            });
        }
    }
}

0

// let’s in the most important, the Timer class has a method called Schedule (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 Handle’s method the post. if you want to know more consultation in the documentation of android "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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.