problems with CountDownTimerWithPause - android

I'm trying to use this timer, like on this question suggested:
https://stackoverflow.com/questions/13806545/how-to-extend-countdown-timer-with-pause,
but doesn't work as expected. The pause/resume works fine, but if I cancel and recreate the timer, then the counting starts from the last paused time. I need to start from the initial value.
For eg the counter's intial value is 3 minutes. If I paused it at 2 minutes, then when I'm trying to create it again it starts from 2 minutes.
Any help?
public class MainActivity extends ButtonMethods implements OnClickListener {
private CountDownTimerWithPause timerPausable = null;
int milis = 180000;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timerPausable = new CountDownTimerWithPause(milis, 1000, true)
{
#Override
public void onTick(long millisUntilFinished)
{
timer.setText("" + millisUntilFinished / 1000);
}
#Override
public void onFinish()
{
timer.setText("180");
DisableRandomButtons();
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bNewWord:
if(clicked == false){
clicked = true;
timerPausable.create();
}
else{
clicked = false;
timerPausable.cancel();
timerPausable=null;
milis=180000;
timerPausable.create();
}
break;
case R.id.imageView2:
tapsound.start();
if(isclicked == false){
isclicked = true;
timerPausable.pause();
}
else{
isclicked = false;
timerPausable.resume();
}
break;

Its hard to say what your exact problem is without seeing your code but what I did was call cancel() on my timer then make it equal to null to reset it. Mine is a little different and I handle it in onBackPressed()
#Override
public void onBackPressed()
{
super.onBackPressed();
timer.cancel(); // timer is a reference to my inner CountDownTimer class
timer = null;
secs = 10;
}
I think this is what you are looking for. It works for me.

Related

Pausing a Android countdowntimer with same button

I have found numerous examples of how to pause a countdowntimer in Android, but each of these examples utilises more than 1 button (pause, resume and cancel).
I want to have one button that when I press it the timer starts, then when I press it again it pauses (cancelling the original timer, capturing the timer value) and resumes when clicked again (taking the captured time from the pause to start off a new counterdowntimer).
Does anyone have an example of how to achieve this? I have tried if else loops in the onClick listener of the button. I have a very crude semi-working example;
if (gameOn == 1) {
if((clkOnTimerBtn % 2)==0) {
isPaused = true; // PAUSE COUNTDOWN TIMER
resumeCountDownTimer(view, "pause");
} else { // RESUME COUNTDOWN TIMER
resumeCountDownTimer(view, "resume");
}
The problem with the above is that this is carried out in the button onclick listener, so if a new CountDownTimer is created inside my resumeCountDownTimer its not possible to access the timer later on to cancel it (pause). I have also tried looking for a way to cancel all countdowntimers, messy if I could, but I couldn't find any examples or references to doing so as this would at least get the desired behaviour even if it isn't the most elegant way.
If I understood you correctly, something like this should work.
public class MainActivity extends AppCompatActivity {
CountDownTimer countDownTimer;
long duration = 100000; //This is the initial time,
long millisecondsLeft = 100000; // This is the time left. At the start it equales the duration.
boolean isCountDownTimerActive = false;
Button startButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.startStop);
final TextView timeLeft = (TextView) findViewById(R.id.timeLeft);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isCountDownTimerActive) {
if (countDownTimer != null)
countDownTimer.cancel();
isCountDownTimerActive = false;
} else {
countDownTimer = new CountDownTimer(millisecondsLeft, 1000) {
#Override
public void onTick(long l) {
millisecondsLeft = l;
timeLeft.setText(" " + l);
}
#Override
public void onFinish() {
}
};
isCountDownTimerActive = true;
countDownTimer.start();
}
}
});
}
}

How to wait for a static string to get a particular value

I am new to android studio and my problem might sound pretty simple but I do badly need a solution.
I need to check whether my static string's value is equal to 1 before executing a particular block of code. It updates every 500ms. It goes from 1 to 16 and then back to 1.
I tried countdowntimer but it didn't work. Please help.
Edit:This is what i am trying.
store=findViewById(R.id.store);
store.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 1; i <= 16; i++){
String m=s;
if (m.equals("1")) {
store();
break;
} else {
new Timer().schedule(new TimerTask() {
#Override
public void run() {
// this code will be executed after 2 seconds
}
}, 500);
}
}
}
});
So essentially what you want to do is, you want to observe the value right?
What you can do instead is, every time you change the value, you invoke a callback, or already explicitly call your block of code.
// this gets called every 500 ms
public static void updateMyValue(String value){
MY_STATIC_STRING = value;
callMyBlockOfCode();
}
This one worked for me. Thank you everyone for your time.
store=findViewById(R.id.store);
store.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String m=s;
if (m.equals("1")) {
store();
} else {
int i=Integer.parseInt(m);
i=(17-i)*delay;
new CountDownTimer(i, 1) {
public void onFinish() {
store();
}
public void onTick(long millisUntilFinished) {
}
}.start();
}
}
});

Android: Count Down Timer .cancel() not working

I'm designing a game and have a problem with countdowntimer not stopping. The timer starts normally as it should, and should stop in the end() method. It works well when ENEMY_HULL is checked as 0 or less, which is calulated seperatly when the users presses a button, and checkEnemyDefeat() is called, but it does not work when ENEMY_CREW is 0. On both situations the message in log cat that the timer is stopped appears, so my guess is that .cancel() is called. I've included all code that seems relevant.
NOTE: All variables including CountDownTimer are global variables
Here is the method containing the timer:
private void BadGameLoop() {
if (GAME_PAUSED == true && !GAME_TIME_STARTED) {
Log.d(" -------- ", "TIMER STARTED");
GAME_PAUSED = false;
GAME_TIME_STARTED = true;
gameTimer = new CountDownTimer(GAME_TIME, UPDATE_RATE) {
#Override
public void onTick(long millisUntilFinished) {
TICKS++;
timer.setText(String.valueOf(GAME_TIME / 1000 - TICKS / 10));
if((CREW_BOARDING > 0 || ENEMY_CREW_BOARDING > 0) && TICKS%10 == 0){
crewFightCalculator();
}
updateViews();
}
#Override
public void onFinish() {
TICKS=0;
GAME_TIME_STARTED = false;
GAME_PAUSED = true;
end();
}
};gameTimer.start();
}
}
Next is the crewFightCalculator method:
private void crewFightCalculator(){
// this just changes the values of ENEMY_CREW (global variable) and then
//calls checkEnemyDefeat() to verify if it should end the timer or not
checkEnemyDefeat();
}
The checkEnemyDefeat and end methods:
private void checkEnemyDefeat(){
if(ENEMY_HULL <= 0){
updateViews();
end();
}else if ( ENEMY_CREW < 1){
updateViews();
end();
}
}
private void end(){
if(GAME_TIME_STARTED){
GAME_TIME_STARTED = false;
gameTimer.cancel();
Log.d("---------"," TIMER STOPPED !");
}
// do more stuff
}
It is simply bizzare to me why it dosen't work. My only guess is that it has something to do with the fact that .cancel() is not triggered by a chain of functions started by user input .
The only solution to this problem that I found, was to modify the onTick method, so that it should check every time if it should run or stop the timer like this:
private void BadGameLoop() {
if (GAME_PAUSED == true && !GAME_TIME_STARTED) {
Log.d(" -------- ", "TIMER STARTED");
GAME_PAUSED = false;
GAME_TIME_STARTED = true;
gameTimer = new CountDownTimer(GAME_TIME, UPDATE_RATE) {
#Override
public void onTick(long millisUntilFinished) {
if(GAME_TIME_STARTED) {
TICKS++;
timer.setText(String.valueOf(GAME_TIME / 1000 - TICKS / 10));
if((CREW_BOARDING > 0 || ENEMY_CREW_BOARDING > 0) && TICKS%10 == 0){
crewFightCalculator();
}
updateViews();
}else{
gameTimer.cancel();
}}
#Override
public void onFinish() {
TICKS=0;
GAME_TIME_STARTED = false;
GAME_PAUSED = true;
end();
}
};gameTimer.start();
}
}
Still, i can't figure out why it didn't work properly before.

How to set a time limit to an android activity

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

Detect when application is idle in Android

I am developing an application that will be running in Kiosk Mode. In this application, if the user didn't do anything in the application within 5 minutes, the application will show a screen saver that is the logo of the application.
My question is, how can I code on detecting IDLE within 5 minutes?
A BETTER SOLUTION HERE...... VERY SIMPLE
I used countdown timer as bellow:
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
}
#Override
public void onTick(long millisUntilFinished) {
}
}
CHEERS..........:)
You should try this, It will Notify with a toast on detecting IDLE 5 minutes.
Handler handler;
Runnable r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
r = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "user Is Idle from last 5 minutes",
Toast.LENGTH_SHORT).show();
}
};
startHandler();
}
#Override
public void onUserInteraction() {
// TODO Auto-generated method stub
super.onUserInteraction();
stopHandler();//stop first and then start
startHandler();
}
public void stopHandler() {
handler.removeCallbacks(r);
}
public void startHandler() {
handler.postDelayed(r, 5*60*1000);
}
I think you could use http://developer.android.com/reference/android/app/Activity.html#dispatchTouchEvent(android.view.MotionEvent) and http://developer.android.com/reference/android/app/Activity.html#dispatchKeyEvent(android.view.KeyEvent) in your App to set a timestamp everytime a userinteraction takes place (simply override the methods and return false at the end so that the events will be propagated to underlying views) - then you can use some kind of timer which checks for the last timestamp of interaction recurringly and trigger your screen saver if your 5 minutes IDLE time are reached.
So in an Activity you simply override the before mentioned Methods like this:
#Override
public boolean dispatchTouchEvent (MotionEvent ev) {
timestamp = System.getCurrentTimeMilis();
return false; // return false to indicate that the event hasn't been handled yet
}
The dispatchKeyEvent and the other methods which you can override to determine user-activity should work fairly similar.
If you're using more than one Activity you may want to create a base class which extends Activity and Override all the dispatchXXXEvent you want to handle and which you than use as base class of all your Activities. But I guess the details of your implementation may be a little bit out of scope for the actual question :)
For the different possibilities of timers you may find useful info here: Scheduling recurring task in Android
try with:
private void startCount(int time) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Add here the code for showing the fullscreenlogo
}
}, time);
}
then, whenever you want to start the count you should add:
startCount(time); // Replace time with 60*5*1000 for 5 mins
if you want to start the count when the app got minimized, then use this:
#Override
public void onPause() {
super.onPause();
startCount(time);
}

Categories

Resources