How to Set a Timer in Android

How to set a timer in android

Standard Java way to use timers via java.util.Timer and java.util.TimerTask works fine in Android, but you should be aware that this method creates a new thread.

You may consider using the very convenient Handler class (android.os.Handler) and send messages to the handler via sendMessageAtTime(android.os.Message, long) or sendMessageDelayed(android.os.Message, long). Once you receive a message, you can run desired tasks. Second option would be to create a Runnable object and schedule it via Handler's functions postAtTime(java.lang.Runnable, long) or postDelayed(java.lang.Runnable, long).

How to set timer in android?

ok since this isn't cleared up yet there are 3 simple ways to handle this.
Below is an example showing all 3 and at the bottom is an example showing just the method I believe is preferable. Also remember to clean up your tasks in onPause, saving state if necessary.



import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class main extends Activity {
TextView text, text2, text3;
long starttime = 0;
//this posts a message to the main thread from our timertask
//and updates the textfield
final Handler h = new Handler(new Callback() {

@Override
public boolean handleMessage(Message msg) {
long millis = System.currentTimeMillis() - starttime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;

text.setText(String.format("%d:%02d", minutes, seconds));
return false;
}
});
//runs without timer be reposting self
Handler h2 = new Handler();
Runnable run = new Runnable() {

@Override
public void run() {
long millis = System.currentTimeMillis() - starttime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;

text3.setText(String.format("%d:%02d", minutes, seconds));

h2.postDelayed(this, 500);
}
};

//tells handler to send a message
class firstTask extends TimerTask {

@Override
public void run() {
h.sendEmptyMessage(0);
}
};

//tells activity to run on ui thread
class secondTask extends TimerTask {

@Override
public void run() {
main.this.runOnUiThread(new Runnable() {

@Override
public void run() {
long millis = System.currentTimeMillis() - starttime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;

text2.setText(String.format("%d:%02d", minutes, seconds));
}
});
}
};


Timer timer = new Timer();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

text = (TextView)findViewById(R.id.text);
text2 = (TextView)findViewById(R.id.text2);
text3 = (TextView)findViewById(R.id.text3);

Button b = (Button)findViewById(R.id.button);
b.setText("start");
b.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Button b = (Button)v;
if(b.getText().equals("stop")){
timer.cancel();
timer.purge();
h2.removeCallbacks(run);
b.setText("start");
}else{
starttime = System.currentTimeMillis();
timer = new Timer();
timer.schedule(new firstTask(), 0,500);
timer.schedule(new secondTask(), 0,500);
h2.postDelayed(run, 0);
b.setText("stop");
}
}
});
}

@Override
public void onPause() {
super.onPause();
timer.cancel();
timer.purge();
h2.removeCallbacks(run);
Button b = (Button)findViewById(R.id.button);
b.setText("start");
}
}


the main thing to remember is that the UI can only be modified from the main ui thread so use a handler or activity.runOnUIThread(Runnable r);

Here is what I consider to be the preferred method.



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

public class TestActivity extends Activity {

TextView timerTextView;
long startTime = 0;

//runs without a timer by reposting this handler at the end of the runnable
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {

@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;

timerTextView.setText(String.format("%d:%02d", minutes, seconds));

timerHandler.postDelayed(this, 500);
}
};

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_activity);

timerTextView = (TextView) findViewById(R.id.timerTextView);

Button b = (Button) findViewById(R.id.button);
b.setText("start");
b.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Button b = (Button) v;
if (b.getText().equals("stop")) {
timerHandler.removeCallbacks(timerRunnable);
b.setText("start");
} else {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
b.setText("stop");
}
}
});
}

@Override
public void onPause() {
super.onPause();
timerHandler.removeCallbacks(timerRunnable);
Button b = (Button)findViewById(R.id.button);
b.setText("start");
}

}


How to display a timer in a TextView in Android?

int time=30;
TextView textTimer = (TextView)findViewById(R.id.timer);

new CountDownTimer(30000, 1000) {

public void onTick(long millisUntilFinished) {
textTimer.setText("0:"+checkDigit(time));
time--;
}

public void onFinish() {
textTimer.setText("try again");
}

}.start();



public String checkDigit(int number) {
return number <= 9 ? "0" + number : String.valueOf(number);
}

How to make a countdown timer in Android?

As shown in the documentation for CountDownTimer:

new CountDownTimer(30000, 1000) {

public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
// logic to set the EditText could go here
}

public void onFinish() {
mTextField.setText("done!");
}

}.start();

how to set a timer and perform an action for it, in android application

You can calculate time difference between current date and user picked date in milliseconds.

    private long getTimeDelay(Calendar userPickedTime){
return userPickedTime.getTimeInMillis() - Calendar.getInstance().getTimeInMillis(); // Time difference
}

Then you can schedule a timer to perform an action at that time.

new Timer().schedule(new TimerTask() {          
@Override
public void run() {
// this code will be executed after time difference between current and user picked time.
}
}, getTimeDelay(userPickedTime));

How to create a simple countdown timer in Kotlin?

You can use Kotlin objects:

val timer = object: CountDownTimer(20000, 1000) {
override fun onTick(millisUntilFinished: Long) {...}

override fun onFinish() {...}
}
timer.start()

How to create timer in Android Studio ( kotlin )?

It most probably happens because the function in onTick() and onFinish() are invoked within the same coroutine that the counter works, so probably you would need to launch another coroutine there to not block the timer scope

Also this CountDownTimer API is experimental at this moment so I guess it is not really recomended to use it, probably you could do something like this:

val timerJob = scope.launch(Dispatcher.IO) {
while (isActive) {
scope.launch { doSomething() }
delay(20L)
}
}

I didn't test it but it should have exactly same behavior (but not blocking the timer), it will run until the scope will cancel itself (f.e. lifecycle scopes) or you will cancel it manually by calling timerJob.cancel()

The isActive boolean takes care of checking if coroutine is still active (so the loop won't "leak")

Unfortunately if you run some heavy stuff in this doSomething() call that will exceed this 20 milisec delay there will happen some concurrency issues so it should be simple

If your "game" is so heavy that this 20 milisec delay will be too small then most probably using coroutines is not the best approach for your idea



Related Topics



Leave a reply



Submit