the program that i am making includes two different count down.
first, user has to type in the password within the time limit and press a button. If user can't input the password before the time limit, then it is over. However, if the user was able to input the password correctly before the time limit, a new timer should start.
public class MalibuCountDownTimer extends CountDownTimer
{
public MalibuCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
#Override
public void onFinish()
{
if(hasPlanted == false) {
text.setText("Time's up!");
mTextView.setText("cya");
btnEnable(false);
startB.setEnabled(false);
}
}
#Override
public void onTick(long millisUntilFinished)
{
text.setText(""+String.format("%02d:%02d:%03d",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)),
TimeUnit.MILLISECONDS.toMillis(millisUntilFinished) - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished))
));
}
}
this is the first timer, and it is working just fine. However, i am having trouble trying to stop this timer when user entered the correct password.
I have created another class of CountDownTimer, and when the user input the correct password within the time limit, the second timer starts. I put a boolean to stop the first timer to do anything when it ends, but I have no idea how I can fully stop that counter.
if(myTimer != null) {
myTimer.cancel();
myTimer = null;
}
This is in order to cancel the timer early. First check if it is null, and if it isn't, apply the cancel method on it. Let me know if this was helpful.
:)
First you have to create service and call that service in main class where timer is running and call the onReceive method
BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Here you check the timer is running or not
timer.cancel();
}
};
Related
I have this code in android studio:
The question is that if I give the button back and the main activity takes me, that is going to continue executing.
How do I make it so that once it's behind, it does not run what's in the onfinished?
new CountDownTimer (40000,1000) {
#Override
public void onTick(long l)
{
crono.setText("00:"+l/1000);
if(contador==10)
{
}
}
#Override
public void onFinish()
{
if(value.equals("tiempo"))
{
crono.setText("00:00");
}
else
{
esperar();
}
}
}.start();
CountDownTimer class help us to implement timer with custom time interval and duration. It provide 2 callback onTick(int millisUntilFinished) which called after each interval and onFinish is called when time duration is completed.
If you want to stop countdown then store instance countdown and call countdown.cancel() in onDestroy or button click(any where by user action)
You can refer this
My project is a radio app and I want to add a sleep timer so that the user can set it to close the app after a specified time.
Please use startTimer(long ms) to start countdown timer and cancel timer to stop. And use wakelock to continue timer after screen off.
CountDownTimer cTimer = null;
void startTimer(long time) {
if(!wakeLock.isHeld()) {
PowerManager mgr = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SonaHeartLock");
wakeLock.acquire();
}
cTimer = new CountDownTimer(time, 1000) {
public void onTick(long millisUntilFinished) {
timerSync = millisUntilFinished;
}
public void onFinish() {
timerSync = 0;
System.exit(0);
}
};
cTimer.start();
}
//cancel timer
void cancelTimer() {
if (cTimer != null) {
timerSync = 0;
cTimer.cancel();
cTimer=null;
if(wakeLock!=null && wakeLock.isHeld())
wakeLock.release();
}
}
Thread.sleep(2000);
will pause for 2 seconds (i.e 2000 ms). In an Android app I wrote several years ago I actually had:
Thread.currentThread().sleep(2000);
but I'm pretty sure the .currentThread() was not needed. I was just learning Java at the time.
See Oracle's doc.
In more detail, what I actually had was a separate task:
class TimerUpdater extends AsyncTask<String, String, Void>{
}
That periodically checked the time (pausing using Thread.sleep()) and displayed a countdown, and at zero set a flag that the main task periodically checked and ended the game when it saw it was set.
My app was terrible code, but I was learning both Java and Android at the same time as fast as I could, to make an app to help my kid in math class.
Android has changed a lot since then, though.
You can get the time from user and after that you can create one background process which count time everytime and check with user time. If both will match then immediately close your app
I want to logout users after they have been inactive for 3 minutes on my app i.e doing nothing for 3 minutes. I have only one Activity and it contains multiple Fragments. How can I achieve this? I tried the answers posted on the same topic but nothing worked. Please can anyone be specific?
Each Activity has an onUserInteraction() function. You can override it and reset a Runnable. If there is no user interaction the Runnable will be called after 3 minutes. Don't forget to remove Runnable onDestory().
Runnable r = new Runnable() {
#Override
public void run() {
// handle timeout
}
};
Handler handler = new Handler();
#Override
public void onUserInteraction() {
super.onUserInteraction();
handler.removeCallbacks(r);
handler.postDelayed(r, 3 * 60 * 1000 );
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(r);
}
Try this
Use CountDownTimer
CountDownTimer timer = new CountDownTimer(15 *60 * 1000, 1000) {
public void onTick(long millisUntilFinished) {
//Some code
}
public void onFinish() {
//Logout
}
};
When user has stopped any action use timer.start() and when user does the action do timer.cancel()
use alarm manager and set alarm for logout
You have two options.
Use an alarm manager and have a broadcast receiver upon receiving the alarm and log out from there. When the user does some activity, restart the alarm. example.
have a Service that you can talk to, and send intents restartTimer. When the timer reaches zero, log out the user.
I am trying to make simple maths game. Aim of the game is to answer so many questions right in a certain time limit.
I have a timer which counts down and calls my final screen to set your highscore. Problem is, when testing the app if the back button is pressed before timer is done, it seems to continue in the background and my highScore screen randomly appears. How can I make this stop?
Here is the code for my timer:
/**
* timer method
*/
public void timer() {
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
Intent i = new Intent(MainActivity.this, HighScoreScreen.class);
i.putExtra("Score", score);
startActivity(i);
resetScore();
finish();
}
}.start();
}
One solution to this very particular problem would be to override onBackPressed and cancel your timer there. On the other hand, if you want to cancel the timer when there is any interruption (e.g. user receives a call while using your app), you could perhaps place the cancel call in a lifecycle method like onStop.
In my onCreate method in my activity i call a method from an object and pass the methods value as 1 which means to start a timer in the objects class. However I want to stop the timer whenever the app closes, loses focus or someone pressed the back button on their device and exited the app. I tried doing this below my onCreate method with an onPause, onStop, onDestroy and entered the methods value as 2 for the object which means to cancel the timer. However my problem is that whenever someone presses the back button on their device and then goes back in to the app the same timer is running twice because the app did not cancel the timer in the onStop, onPause or onDestroy. Why didn't the onStop, onPause and onDestroy stop the timer and how do i make it stop the timer so two arent running when the app is reopened?
Activity below
Ship mShip = new Ship(0,0,0);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
mShip.timerStart(1);
}
#Override
public void onPause()
{
super.onPause();
mShip.timerStart(2);
}
#Override
public void onStop()
{
super.onStop();
mShip.timerStart(2);
}
#Override
public void onDestroy()
{
super.onDestroy();
mShip.timerStart(2);
}
Ship Class below
public static int counter = 0;
public static int counterPerSec = 5;
TimerClass startTimer = (TimerClass) new TimerClass(2000,1000)
{
#Override
public void onFinish() {
counter += counterPerSec;
this.start();
}
};
public void timerStart(int x) {
if(x == 1)
{
startTimer.start();
}
if(x == 2)
{
startTimer.cancel();
}
}
Timer Class
public class TimerClass extends CountDownTimer {
public TimerClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override // when timer is finished
public void onFinish() {
this.start();
}
#Override // on every tick of the timer
public void onTick(long millisUntilFinished) {
}
}
I can not see, why your timer is not canceled. But there is another bug in your code: You can not pause and resume a countdown timer by calling resume and start.
If your time gets canceled, you should save the old timer vaules. And if your timer has to be resumed, you can create a new timer with the old timer values. See: Android: How to pause and resume a Count Down Timer?
To your question: Can you debug and check if onPause, onStop, onDestroy is called? Is there any exception thrown? Do you have any compile warnings?
Last important question: How do you know that two timers are running?
Well, I think I can correctly assume that onPause, onStop, and onDestroy are executing, so I would venture to guess that there is a bug in your TimerClass class.