How to dispose CountDownTimer - android

I have main class called "MainActivity" and I'm lanuching it few times in my App.
private static CountDownTimer timer;
private static final long startTime = 15 * 1000;
private static final long interval = 1 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = new StageCountDownTimer(startTime, interval);
}
private class StageCountDownTimer extends CountDownTimer {
public StageCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
//STARTTING NEW ACTIVITY
}
#Override
public void onTick(long millisUntilFinished) {
}
}
Sometimes user need to close this activity before count down ends, and return to the this activity again. And then new count down is launching but the old one execute the code in onFinish() when previous count down ends. Everything works great when I start this code once. How to cancel/dispose/destroy this timer after exiting from activity? I tried timer.cancel() and nothing happen.
EDIT
I think I solved my problem by setting CountDownTimer timer as a public and in other Activity i'm just using MainActivity.timer.cancel()

You can use:
if (isFinishing()) {
CountDownTimer.cancel();
}
so if the acitvity is finishing, the countdowntimer gets canceled. and next time you open the acitvity, new countdowntimer will be up.

In addition to timer.cancel() (which should work) you can do in your timer's onFinish():
#Override
public void onFinish() {
if(!MainActivity.this.isFinishing()) {
// Start new activity...
}
}

I think I solved my problem by setting CountDownTimer timer as a public and in other Activity i'm just using MainActivity.timer.cancel()

Related

Reset value to default when using OnclickListener in Android

I'm trying to do some example about countdown timer using Button and set OnclickListener for that Button. My Default value is 10 and it will be decrease each second, how can i reset my value back to 10?
CountDownTimer cannot be restarted, it can only be used once. You either have to create your own count down class that can handle being restarted, or just create a new instance of your CountDownTimer and cancel the old instance.
See the example code below where we have a CountDownTimer that counts down for 10 seconds in 1 second intervals, a Button that resets the timer when clicked (by cancelling the current timer and starting a new one), and a TextView that displays the time left in the current timer.
public class YourActivity extends Activity {
private CountDownTimer countDownTimer;
private TextView timerDisplayTextView;
private static final long TEN_SECONDS = TimeUnit.SECONDS.toMillis(10);
private static final long COUNTDOWN_INTERVAL = TimeUnit.SECONDS.toMillis(1);
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Button myButton; // initialized here
// timerDisplayTextView initialized here
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
countDownTimer.cancel();
countDownTimer = getNewCountDownTimer(TEN_SECONDS);
countDownTimer.start();
showTimeInTextView(TEN_SECONDS);
}
});
countDownTimer = getNewCountDownTimer(TEN_SECONDS);
countDownTimer.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
countDownTimer.cancel();
}
private void showTimeInTextView(long millisecondsLeft) {
timerDisplayTextView.setText(TimeUnit.MILLISECONDS.toSeconds(millisecondsLeft) + " seconds left");
}
private CountDownTimer getNewCountDownTimer(long length) {
return new CountDownTimer(length, COUNTDOWN_INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
showTimeInTextView(millisUntilFinished);
}
#Override
public void onFinish() {
}
};
}
}

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

How to keep an activity in foreground for 15 seconds and then dismiss it?

I need to start an activity at time 0, keep it in the foreground for 15 seconds and then stop the activity. What is the best way of doing this?
Thanks!
You can try:
int duration = 15000; // milliseconds
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, duration);
This will automatically finish your activity after 15 seconds.
Use AlarmManager to call the activity back in fifteen seconds, an example of using AlarmManager can be seen here: http://code4reference.com/2012/07/tutorial-on-android-alarmmanager/.
The BroadcastReciever that is called should be inside the main Activity and it should call finish().
You're looking for a splashActivity :
public class SplashScreenActivity extends Activity {
private static final int DURATION = 15000; // 15 seconds
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, DURATION);
}
}
You can see here a full working example.

Android: Timer onTick problem

Hi I'm working on one of my project then I encountered this problem, well I don't know if it is a bug or something I just want to share hoping to get some answer to enlighten my day. So here's the problem:
I made a countdown timer for my project which will run for 2 minutes (that will be 120 seconds) 1000 is the interval time (1000ms = 1s) then I set a checker, an integer of 120 (declared globally) which will be diminished by one each time the timer ticks. The integer will be shown on a textView counting down. then will show a message when the integer reaches the onFinish of the timer. That message will give how much time I've spent by deducting the declared integer by 120.
The problem here is that the timer stops before it reaches 1 given that it will not be deducted by the last tick. The hardest part is that sometimes it stops with 4 or even 5 on the remaining time. Can Anyone help me about this one? Thanks in advance!
Here's my code for further understanding:
//declared a timer
int timer = 120;
//starts the timer
gameTimer = new gameTimer(120000, 1000);
gameTimer.start();
private class gameTimer extends CountDownTimer{
public gameTimer(long startTime, long interval)
{
super(startTime, interval);
}
public void onTick(long millisUntilFinished)
{
//on tick deduct timer by 1
timer -= 1;
TextView timer1 = (TextView)findViewById(R.id.textView1);
timer1.setText(""+timer);
}
public void onFinish()
{
//PERFORM END ACTION UPON FINISHING THE GAME
endtime = 120 - timer;
TextView endtime1 = (TextView)findViewById(R.id.textView2);
1.setText(""+endtime);
}
}
First *: this is your class that extended the* CountDownTimer :
public class GameTimer extends CountDownTimer{
private YourActivity context;
private int timer = 120;
private int endtime;
private TextView timer1,endTime1;
public gameTimer(YourActivity context, long startTime, long interval)
{
// passing the context of your activity
this.context = context;
//get the textView to display results
timer1 = (TextView)this.context.findViewById(R.id.textView1);
endTime1 = (TextView)this.context.findViewById(R.id.textView2);
super(startTime, interval);
}
public void onTick(long millisUntilFinished)
{
//on tick deduct timer by 1
timer -= 1;
//override the method runOnUIThread
context.runOnUiThread(new Runnable(){
#override
public void run(){
timer1.setText(""+timer);
}
});
}
public void onFinish()
{
//PERFORM END ACTION UPON FINISHING THE GAME
endtime = 120 - timer;
//override the method runOnUIThread
context.runOnUiThread(new Runnable(){
#override
public void run(){
endTime1.setText(""+endtime);
}
});
}
}
Second : in your activity ( on the method onCreate() , instanciate your GameTimer and start it :
//instanciate the GameTimer and pass the context to it
GameTimer gameTimer = new GameTimer(this, 120000, 1000);
gameTimer.start();

How do I set a completion activity for a CountDown timer in Android?

I am trying to create a countdown timer that counts down for 60 seconds (optionally skippable by the user). That part of the code works. How do I make it so an action is taken upon the completion of the countdown timer (the same action as the button does, ending the activity).
public void startCountdown(int total, final int increase) {
final TimerClassExtended timer = new TimerClassExtended(total,1000);
timer.start();
Button skip = (Button)findViewById(R.id.skip);
skip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
timer.cancel();
setResult(RESULT_OK);
finish();
}
});
}
Figured it out, had to modify the following line. But I can't answer myself for 8 hours...
For future reference, TimerClassExtended is just a class I made that extends CountDownTimer so I could add extra methods that I needed.
final TimerClassExtended timer = new TimerClassExtended(total,1000) {
public void onFinish() {
setResult(RESULT_OK);
finish();
}
};
I have no knowledge of the class you are using, but you might consider using a TimerTask and scheduling it for 60000ms.
Timer timer = new Timer();
timer.schedule( task, 60000 );
Since I had a custom class I added the following:
final TimerClassExtended timer = new TimerClassExtended(total,1000) {
public void onFinish() {
setResult(RESULT_OK);
finish();
}
};

Categories

Resources