I am not able to stop the Android Timer - android

I am using following code to run a timer in my Android App.
I want to stop the Timer exactly when the time reaches to
1 Minute
2 Minute
3 Minute
and so on.
But I am not able to understand how to do it.
Any Help Will be appreciated.
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 MainActivity 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.activity_main);
timerTextView = (TextView) findViewById(R.id.text);
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");
}
}

Why not use the CountDownTimer class?
You can simply instantiate it as:
int bigTime = 1000000000;
//1000 is ms after which the timer ticks (that is, the method gets called and so, you can update your view)
CountDownTimer countDownTimer = new CountDownTimer(bigTime, 1000) {
public void onTick(long millisUntilFinished) {
updateTime();
//you can write the code to update your view in this method
}
#Override
public void onFinish() {
Log.i("Get a life bro..."," 31 years have passed!");
}
};
Now, in your onCreate() method, according to the clicklisteners on your start/stop button, you can simply start or stop the timer:
countDownTimer.start();
if(seconds == 0 && minutes > 0) {
// get the values of seconds and minutes from the view.
countDownTimer.cancel();
}
Just in case you want to pause the timer and start from the paused time, you can store the value of the time in milliseconds, stop the timer and restart it after adding the value you stored.

Related

how to continue timer in app when come back from onRestart state

i've created a small app of memory game. in that app i have created a timer that show the time that take the user to finish the game. my problem is that the timer freeze after i go to another page (like home screen) and back to the game- the time remain at the same time it was stopped.....(i khnow it related somehow to onRestarte() method but dont know what to do..) i want that the timer will continue at the same time it has been stopped. (like if the user have an incall in the middle of the game and then want to continue).
package com.example.kineret.memorygame;
public class Game4x4Activity extends AppCompatActivity implements View.OnClickListener{
TextView timerTextView;
long startTime = 0;
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
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game4x4);
timerTextView = (TextView) findViewById(R.id.timerTextView4x4);
}
#Override
public void onPause() {
super.onPause();
timerHandler.removeCallbacks(timerRunnable);
}
#Override
public void onClick(View view) {
if(newGame) {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
newGame = false;
}
// rest of my code...
}
i have edited your code. plz try this
public class Game4x4Activity extends AppCompatActivity implements View.OnClickListener{
// make a new variable
static long elapsedTime = 0;
TextView timerTextView;
long startTime = 0;
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
// change here
long millis = (System.currentTimeMillis() - startTime) + elapsedTime;
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
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game4x4);
timerTextView = (TextView) findViewById(R.id.timerTextView4x4);
}
#Override
public void onPause() {
// change here
elapsedTime = elapsedTime + (System.currentTimeMillis() - startTime);
timerHandler.removeCallbacks(timerRunnable);
super.onPause();
}
#Override
public void onResume() {
super.onResume();
// change here
if(!newGame) {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
}
}
If the user gets a phone call your app will call onPause then if they finish their phone call and play your game your activity will get onResume called.
in onPause save the system time, in onResume get the latest system time. Take these away from each other (in onResume) and you will have the time that the user was not in your app, you can then add this to your timer before you restart it.
You may also have to persist this time with onSaveInstanceState at other points.

how to start a countdown timer on activity start without any action performed?

I have written a program for a countdown timer but the countdown starts only on button click , but i want it to start without the button click , can anyone suggest me how to do it without the button click ?
Here is the code for countdown timer
public class MainActivity extends ActionBarActivity {
CountDownTimer countDownTimer;
boolean timehasstarted = false;
Button btnStart;
TextView timer;
long startTime = 30 * 1000;
long interval = 1 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.button1);
timer = (TextView) findViewById(R.id.timer);
timer.setText(timer.getText() + String.valueOf(startTime / 1000));
btnStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!timehasstarted) {
countDownTimer.start();
timehasstarted = true;
timer.setText("Stop");
} else {
countDownTimer.cancel();
timehasstarted = false;
timer.setText("Restart");
}
}
});
countDownTimer = new CountDownTimer(startTime, interval) {
#Override
public void onTick(long millisUntilFinished) {
timer.setText("" + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
timer.setText("Time's Up!");
}
};
}
Move your timer code to onCreate() method of the Activity instead of the onClick() method
This will start the timer on activity start.
And also you can use timer.cancel() to cancel the timer when the activity is stopped or not currently active
if you want to turn on the countdown after a particular time say after 2 sec then you can use TimerTask for this for exmaple :
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
}
}, 2000);

android: do some code on media player special time

I'm newbie in android programming..
I have a media player in my activity to play a sound.
I want to do some code on a special time that the media player is playing. I mean I want to do code1 during media player is in 0 to 5sec, and do code2 during 5 to 14 and do code3 during 14 to 18sec.
here's my timer code and I don't know how to run my codes on special times..
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 MainActivity 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.activity_main);
timerTextView = (TextView) findViewById(R.id.text);
Button b = (Button) findViewById(R.id.button1);
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.button1);
b.setText("start");
}
}
This isn't the most elegant solution, especially if all your time blocks will be exactly 5 seconds apart but if you set initalTime when the media player starts, it should work. Further documentation for uptimeMillis() and other Android timer methods are linked here
int initialTime= SystemTimer.uptimeMillis();
while (mediaIsRunning){
int currentTime=SystemTimer.uptimeMillis();
int elapsed=currentTime-initialTime;
if (elapsed<=5000){ // 5 seconds
//your code 1
}
else if (elapsed<=10000){ //10 seconds
//code 2
}
//etc ...
}

How to display the timer in android

I want to display the timer in TextView in the format of like [ 19:59].so when i click the start button ,the timer will display like this for example,i want to set upto 20 mintues,it will display like [19:58][19:87].can anyone give some ideas or example code?
You can use the CountDownTimer.
http://developer.android.com/reference/android/os/CountDownTimer.html
TextView _tv = (TextView) findViewById( R.id.textView1 );
new CountDownTimer(20*60000, 1000) {
public void onTick(long millisUntilFinished) {
_tv.setText("seconds remaining: " +new SimpleDateFormat("mm:ss:SS").format(new Date( millisUntilFinished)));
}
public void onFinish() {
_tv.setText("done!");
}
}.start();
To cancel just call cancel on the timer.
public final void cancel()
Cancel the countdown.
package com.example.testproject;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity {
public int seconds = 60;
public int minutes = 10;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView tv = (TextView) findViewById(R.id.main_timer_text);
tv.setText(String.valueOf(minutes)+":"+String.valueOf(seconds));
seconds -= 1;
if(seconds == 0)
{
tv.setText(String.valueOf(minutes)+":"+String.valueOf(seconds));
seconds=60;
minutes=minutes-1;
}
}
});
}
}, 0, 1000);
}
}
//start button click
CountDown timer = new CountDown(180000, 1000);
timer.start();
//stop button click
timer.stop();
//countdown class
public class CountDown extends CountDownTimer {
public CountDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
long ms = millisUntilFinished;
String text = String.format("%02d\' %02d\"",
TimeUnit.MILLISECONDS.toMinutes(ms) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(ms)),
TimeUnit.MILLISECONDS.toSeconds(ms) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(ms)));
textViewTimer.setText(text);
}
#Override
public void onFinish() {
textViewTimer.setText("ffinish");
}
}
do it this way activity_timer.xml
<android.support.v7.widget.LinearLayoutCompat
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Chronometer
android:id="#+id/chronometer2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.v7.widget.LinearLayoutCompat>
And in Activity
public class TimerActivity extends AppCompatActivity {
private Chronometer chronometer2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
chronometer2 = findViewById(R.id.chronometer2);
chronometer2.start();
}
}
You can also use stop
chronometer2.stop();
Re Start
chronometer2.setBase(SystemClock.elapsedRealtime());
chronometer2.start();
Here I have use Timer class to display timer
public class FourthActivity extends AppCompatActivity {
Button startButton, pauseButton;
TextView timerValue;
Timer timer;
int seconds = 0, minutes = 0, hour = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fourth);
bindView();
timer = new Timer();
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (seconds == 60) {
timerValue.setText(String.format("%02d", hour) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
minutes = seconds / 60;
seconds = seconds % 60;
hour = minutes / 60;
}
seconds += 1;
timerValue.setText(String.format("%02d", hour) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
}
});
}
}, 0, 1000);
}
});
}
private void bindView() {
timerValue = (TextView) findViewById(R.id.timerValue);
startButton = (Button) findViewById(R.id.startButton);
}
}
In layout, there are one TextView and one Button to start timer. I have use Timer class method scheduleAtFixedRate. Time will be displayed in hh:mm:ss form.
This can be done using cronometer, the most main reason is supporting API 1+, which is quite impressive rather than TextClock, which supports API 17+.
You can do lots of other things with cronometer. for example you can set start time in it
chronometer.setBase(SystemClock.elapsedRealtime());
You can also learn about it more here.
I made code for timer display in textView.The formate is for e.g:- 02:59:00
You can follow this link to get the Step By Step Code.
https://stackoverflow.com/a/58316149/11613683

android timer problem

I have question. is this code timer correct;]? or i can do it more easily
package timer2.android;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Timer2Activity extends Activity {
private TextView tv;
private Timer myTimer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.textView1);
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 1000);
}
private void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
}
long mStartTime = System.currentTimeMillis();
private Runnable Timer_Tick = new Runnable() {
public void run() {
final long start = mStartTime;
long millis = System.currentTimeMillis() - start;
int seconds = (int) (millis / 1000);
int minutes = (int) (seconds / 60);
seconds = seconds % 60;
if (seconds < 10)
{
tv.setText("" + minutes + ":0" + seconds);
}
else
{
tv.setText("" + minutes + ":" + seconds);
}
//a++;
//This method runs in the same thread as the UI.
//Do something to the UI thread here
}
};
}
Can't see anything wrong here. But you should use Handler for timers as it does not create additional threads. See example here: Repeat a task with a time delay?

Categories

Resources