I know there is a post like this but it does not answer the question clearly.
I have a little game where you tap a head and it moves to a random position and you get +1 to score. Meanwhile there is a timer counting down from 60000 (60 seconds) and displaying below.
How can I make it so whenever the head is tapped, it adds a second to the timer?
new CountDownTimer(timer, 1) {
public void onTick(long millisUntilFinished) {
textTimer.setText("Timer " + millisUntilFinished/1000);
}
public void onFinish() {
Intent intent = new Intent(MainActivity.this, Gameover.class);
startActivity(intent);
}
}.start();
and in the onClickListner event I have:
timer=timer+1000;
It currently doesn't work as in there is no time added on the click.
Any help would be appreciated :)
You can't change the time of a scheduled timer. The only way to achieve what you are trying to do is by cancelling the timer and setting up a new one.
public class CountdownActivity extends Activity implements OnTouchListener{
CountDownTimer mCountDownTimer;
long countdownPeriod;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_countdown);
countdownPeriod = 30000;
createCountDownTimer();
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mCountDownTimer != null)
mCountDownTimer.cancel();
createCountDownTimer();
return true;
}
private void createCountDownTimer() {
mCountDownTimer = new CountDownTimer(countdownPeriod + 1000, 1) {
#Override
public void onTick(long millisUntilFinished) {
textTimer.setText("Timer " + millisUntilFinished / 1000);
countdownPeriod=millisUntilFinished;
}
#Override
public void onFinish() {
Intent intent = new Intent(MainActivity.this, Gameover.class);
startActivity(intent);
}
};
}
}
Related
I use CountDownTimer in my code and when i run app i have one problem that is when i go to next level ( go to next activity ) the timer should be stop and dont run the onfinish method but when the first level timer down it run the onfinish method and go to activity GameOver .
I use Intent to move between my activity and my CountDownTimer is :
new CountDownTimer(timeoflevel, 1000) {
public void onTick(long millisUntilFinished) {
txtclock2.setText("Time: " + millisUntilFinished / 1000);
//here you can have your logic to set text to edittext
}
public void onFinish() {
txtclock2.setText("..Finish..");
Intent intent = new Intent(Play.this , GameOver.class);
startActivity(intent);
}
}.start();
Sorry for my easy question and thanks for reading .
CountDownTimer countDownTimer;
countDownTimer = new CountDownTimer(timeoflevel, 1000) {
public void onTick(long millisUntilFinished) {
txtclock2.setText("Time: " + millisUntilFinished / 1000);
//here you can have your logic to set text to edittext
}
public void onFinish() {
txtclock2.setText("..Finish..");
Intent intent = new Intent(Play.this , GameOver.class);
startActivity(intent);
}
}.start();
// and in OnStop
public void onStop(){
countDownTimer.cancel();
}
You should call countDownTimer.cancel() before starting next level. It will cancel the counDownTimer and will not call onFinish.
public void onStop(){
//Cancel your timer here before going to next activity.
}
CountDownTimer countDownTimer;
//in on Resume()
countDownTimer = new CountDownTimer(timeoflevel, 1000) {
public void onTick(long millisUntilFinished) {
txtclock2.setText("Time: " + millisUntilFinished / 1000);
//TODO perform operation
}
public void onFinish() {
txtclock2.setText("..Finish..");
Intent intent = new Intent(Play.this , GameOver.class);
startActivity(intent);
}
}.start();
// Cancel Timer in onPause()
public void in onPause(){
countDownTimer.cancel();
}
I want to make a method (service, alarm, etc.) that can be calculated after x downtime user with the app
Which closes the current activity
and will send the initial activity (login)
Thank you very much
http://androidbite.blogspot.in/2012/11/android-count-down-timer-example.html
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
//here you can have your logic to set text to edittext
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Refer this link and some examples on countdown timer if you want to use this.
I answer
code is
private long startTime=15*60*1000; // 15 MINS IDLE TIME
private final long interval = 1 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countDownTimer = new MyCountDownTimer(startTime, interval);
}
#Override
public void onUserInteraction(){
super.onUserInteraction();
//Reset the timer on user interaction...
countDownTimer.cancel();
countDownTimer.start();
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
//DO WHATEVER YOU WANT HERE
// CIERRA LA APP MATANDO EL PROCESO Y VUELVE A ABRIRLO.
android.os.Process.killProcess(android.os.Process.myPid());
}
#Override
public void onTick(long millisUntilFinished) {
}
}
use
act.finishAffinity();
act.startActivity(new Intent(act, actMain.class));
I implemented an app, inside there's a button to start a CountDownTimer and a TextView to display time left. Someone told me that the timer should run on other thread rather than on main thread, but as I start the timer normally, it 's on the main thread :
_timer = new CountDownTimer(min * 60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
tick();
setChanged();
notifyObservers();
clearChanged();
Log.v("THREAD TIMER : ", "" + Looper.myLooper().getThread().getName());
}
#Override
public void onFinish() {
end = true;
setChanged();
notifyObservers();
clearChanged();
}
};
I use an Observer to update the TextView each time the timer tick, and the code which update the TextView, is also run on the main thread (I confirm it with Looper.myLooper().getThread().getName()). But it didn't affect the TextView at all, but it did print out the debugging that I put to test. Anybody have any idea to fix this ?
Now this is even more confused. I extract the timer part, and formed a new project. Now, it worked. But of course it still didn't work on my actual project :
public class MainActivity extends Activity {
long TIME = 60000;
CountDownTimer _timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button) findViewById(R.id.button_1);
Button b2 = (Button) findViewById(R.id.button_2);
final TextView t1 = (TextView) findViewById(R.id.timer_1);
TextView t2 = (TextView) findViewById(R.id.timer_2);
setUpButton1(b1, t1);
setUpButton2(b2, t2);
}
private void setUpButton2(final Button b2, final TextView t2){
final MyTimer myTimer = new MyTimer();
Observer ob = new Observer() {
#Override
public void update(Observable observable, Object data) {
//t2.setText(myTimer.toString());
t2.post(new Runnable() {
#Override
public void run() {
t2.setText(myTimer.toString());
}
});
Log.v("CLASS TIMER :", Looper.myLooper().getThread().getName() + " thread -- " + myTimer.toString());
}
};
myTimer.addObserver(ob);
b2.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
if(b2.isPressed()){
b2.setPressed(false);
myTimer.stopTimer();
}else{
b2.setPressed(true);
myTimer.startTimer();
}
}
return true;
}
});
}
private void setUpButton1(final Button b1, final TextView t1){
b1.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP){
if (b1.isPressed() == true){
b1.setPressed(false);
_timer.cancel();
} else {
b1.setPressed(true);
_timer = new CountDownTimer(TIME, 1000) {
#Override
public void onTick(long millisUntilFinished) {
t1.setText("" + millisUntilFinished/1000);
TIME = millisUntilFinished;
}
#Override
public void onFinish() {
}
};
_timer.start();
}
}
return true;
}
});
}
}
Timer class :
public class MyTimer extends Observable{
CountDownTimer myTimer;
long TIME = 60000;
public MyTimer(){
}
public void startTimer(){
myTimer = new CountDownTimer(TIME, 1000) {
#Override
public void onTick(long millisUntilFinished) {
TIME = millisUntilFinished;
setChanged();
notifyObservers();
clearChanged();
}
#Override
public void onFinish() {
}
};
myTimer.start();
}
public void stopTimer(){
myTimer.cancel();
}
public String toString(){
return "" + TIME/1000;
}
}
Anybody have any idea what happened here ? Why it worked in this case, but not work when it's in the whole project ?
I have a game where if a user touches the wrong button he goes to the highscores page and if he clicks the right one he goes to the next level. What I would like to do is make it so if the user does absolutely nothing for 1.5 seconds (fast-paced game) then it automatically intents him back to the scores.class activity. I am new to programming so anything helps!!! Thanks.
This will give you an idea:
private MainActivity context;
private CountDownTimer countDownTimer;
public boolean timerStopped;
/** Called when the activity is first created. */
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
startTimer();
// method looks at users choice, example
/* if (answer == true){
stopTimer();
// go to next question and start timer again..
}
else{
// do something
}
*/
}
/** Starts the timer **/
public void startTimer() {
setTimerStartListener();
timerStopped = false;
}
/** Stop the timer **/
public void stopTimer() {
countDownTimer.cancel();
timerStopped = true;
}
/** Timer method: CountDownTimer **/
private void setTimerStartListener() {
// will be called at every 1500 milliseconds i.e. every 1.5 second.
countDownTimer = new CountDownTimer(1500, 1500) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
// Here do what you like...
Intent intent = new Intent(context, Scores.class);
startActivity(intent);
}
}.start();
}
have you tried with CountDownTimer?
Here is an example:
new CountDownTimer(1500, 1500) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
// Here do what you like...
}
}.start();
To fix the error mentioned:
MainActivity context;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
new CountDownTimer(1500, 1500) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
// Here do what you like...
Intent intent = new Intent(context, Score.class);
startActivity(intent);
}
}.start();
I want to do countdown timer with pause and restart.Now i am displaying countdown timer By implenting ontick() and onfinish().please help me out.HEre is th code for countdown timer
final CountDownTimer Counter1 = new CountDownTimer(timervalue1 , 1000)
{
public void onTick(long millisUntilFinished)
{
System.out.println("onTick method!"(String.valueOf(millisUntilFinished/1000)));long s1=millisUntilFinished;
}
public void onFinish()
{
System.out.println("Finished!");
}
}
in onTick method..save the milliseconds left
long s1=millisUntilFinished;
when you want to pause the timer use..
Counter.cancel();
when you want to resume create a new countdowntimer with left milliseconds..
timervalue=s1
counter= new Counter1();
counter.start();
See this link
I would add something to the onTick handler to save the progress of the timer in your class (number of milliseconds left).
In the onPause() method for the activity call cancel() on the timer.
In the onResume() method for the activity create a new timer with the saved number of milliseconds left.
Refer the below links
LINK
LINK
My first answer on stackOverFlow, hope it should help :) ...
This is how I solved the problem, control timer from Fragment, Bottomsheet, Service, Dialog as per your requirement, keep a static boolean variable to control.
declare in your Activity:
long presetTime, runningTime;
Handler mHandler =new Handler();
Runnable countDownRunnable;
Toast toastObj;
public static boolean shouldTimerRun = true;
TextView counterTv;
In onCreate:
presetTime =60000L;
runningTime= presetTime;
//setting up Timer
countDownRunnable=new Runnable() {
#Override
public void run() {
if (shouldTimerRun) //if false, it runs but skips counting
{
counterTv.setText(simplifyTimeInMillis(runningTime));
if (runningTime==0) {
deployToast("Task Completed"); //show toast on task completion
}
runningTime -= 1000;
presetTime = runningTime; //to resume the timer from last position
}
mHandler.postDelayed(countDownRunnable,1000); //simulating on-tick
}
};
mHandler.post(countDownRunnable); // Start our CountdownTimer
Now, whenever you want to pause the timer change the value of shouldTimerRun false and to resume make it true.
#Override
public void onResume() {
super.onResume();
shouldTimerRun=true;
}
#Override
public void onPause() {
super.onPause();
shouldTimerRun=false;
deployToast("Timer is paused !!");
}
Helping methods: (can be skipped)
public static String simplifyTimeInMillis(long time) {
String result="";
long difference = time;
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
if (difference<1000){
return "0";
}
if (difference>=3600000) {
result = result + String.valueOf(difference / hoursInMilli) + "hr ";
difference = difference % hoursInMilli;
}
if (difference>=60000) {
result = result + String.valueOf(difference / minutesInMilli) + "m ";
difference = difference % minutesInMilli;
}
if (difference>=1000){
result = result + String.valueOf(difference / secondsInMilli) + "s";
}
return result;
}
public void deployToast(String msg){
if (toastObj!=null)
toastObj.cancel();
toastObj = Toast.makeText(mContext,msg,Toast.LENGTH_SHORT);
toastObj.show();
}
I'm using two private vars in this case:
private long startPauseTime;
private long pauseTime = 0L;
public void pause() {
startPauseTime = System.currentTimeMillis();
}
public void resumen(){
pauseTime += System.currentTimeMillis() - startPauseTime;
}
I am afraid that it is not possible to pause or stop CountDownTimer and pausing or stopping in onTick has no effect whatsoever user TimerTask instead.
Set up the TimerTask
class UpdateTimeTask extends TimerTask {
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timeLabel.setText(String.format("%d:%02d", minutes, seconds));
}
}
if(startTime == 0L) {
startTime = evt.getWhen();
timer = new Timer();
timer.schedule(new UpdateTimeTask(), 100, 200);
}
You can add event listener's like this..
private Handler mHandler = new Handler();
...
OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
if (mStartTime == 0L) {
mStartTime = System.currentTimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
}
};
OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
mHandler.removeCallbacks(mUpdateTimeTask);
}
};
For more refer to Android Documentation.
//This timer will show min:sec format and can be paused and resumed
public class YourClass extends Activity{
TextView timer;
CountDownTimer ct;
long c = 150000; // 2min:30sec Timer
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.YourXmlLayout);
timer = (TextView)findViewById(R.id.Yourtimer)
startTimer(); // it will start the timer
}
public void startTimer(){
ct = new CountDownTimer(c,1000) {
#Override
public void onTick(long millisUntilFinished) {
// Code to show the timer in min:sec form
// Here timer is a TextView so
timer.setText(""+String.format("%02d:%02d",millisUntilFinished/60000,(millisUntilFinished/1000)%60));
c = millisUntilFinished; // it will store millisLeft
}
#Override
public void onFinish() {
//your code here
}
};
ct.start();
}
/*===========================================================
*after creating this you can pause this by typing ct.cancel()
*and resume by typing startTimer()*/
public class MainActivity extends AppCompatActivity {
TextView textView;
CountDownTimer ctimer;
boolean runCountDown;
private long leftTime;
private static final long MILL_IN_FUTURE = 6000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view);
textView.setText("Click to start");
textView.setOnClickListener(this::clickStartAndPauseAndResume);
leftTime = MILL_IN_FUTURE;
}
public void clickStartAndPauseAndResume(View view) {
if (!runCountDown) {
long time = (leftTime == 0 || leftTime == MILL_IN_FUTURE) ? MILL_IN_FUTURE : leftTime;
ctimer = new CountDownTimer(time, 1) {
#Override
public void onTick(long l) {
leftTime = l;
textView.setText(l + "ms");
}
#Override
public void onFinish() {
textView.setText("Done");
leftTime = 0;
runCountDown = false;
textView.postDelayed(new Runnable() {
#Override
public void run() {
textView.setText("Click to start");
}
}, 1000);
}
}.start();
runCountDown = true;
} else {
ctimer.cancel();
textView.setText(textView.getText() + "\n Click to resume");
runCountDown = false;
}
}
}
A nice and simple way to create a Pause/Resume for your CountDownTimer is to create a separate method for your timer start, pause and resume as follows:
public void timerStart(long timeLengthMilli) {
timer = new CountDownTimer(timeLengthMilli, 1000) {
#Override
public void onTick(long milliTillFinish) {
milliLeft=milliTillFinish;
min = (milliTillFinish/(1000*60));
sec = ((milliTillFinish/1000)-min*60);
clock.setText(Long.toString(min)+":"+Long.toString(sec));
Log.i("Tick", "Tock");
}
The timerStart has a long parameter as it will be reused by the resume() method below. Remember to store your milliTillFinished (above as milliLeft) so that you may send it through in your resume() method. Pause and resume methods below respectively:
public void timerPause() {
timer.cancel();
}
private void timerResume() {
Log.i("min", Long.toString(min));
Log.i("Sec", Long.toString(sec));
timerStart(milliLeft);
}
Here is the code for the button FYI:
startPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(startPause.getText().equals("Start")){
Log.i("Started", startPause.getText().toString());
startPause.setText("Pause");
timerStart(15*1000);
} else if (startPause.getText().equals("Pause")){
Log.i("Paused", startPause.getText().toString());
startPause.setText("Resume");
timerPause();
} else if (startPause.getText().equals("Resume")){
startPause.setText("Pause");
timerResume();
}