Reset a timer in android - android

I have a timer running in my android application. I want that after user interaction the timer should reset itself? is there any function like reset() that resets the timer? What is the procedure to reset the timer?

try this I have used this code every where... when I need to restart timer. working fine for me.
// FOR CANCELING TIMER AND RESTARTING
my_timer.cancel();
if (my_timer == null) {
my_timer = new Timer(true);
}
if (my_timer != null) {
my_timer_task = new TimerTask() {
#Override
public void run() {
// CODE YOU WANT TO EXECUTE WHEN TIMER HITS.
}
};
}
hope it will help you.

Related

Reusing timer in android

In my android app, I have the following relevant piece of code:
/*Code outside*/
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Timer t = new Timer();
t.scheduleAtFixedRate(
new TimerTask(){
public void run(){
stuffToBeDone();
}
},someVariableDelay,someVariablePeriod);
}
}
Everything was going fine until I noticed that stuffToBeDone() was running once for every time I pressed the button. As far as I understand, every time onClick() is called and the old Timer should not exist anymore, but somehow the TimerTask survives.
In the second button click, I no longer have a reference to the first Timer to cancel() it (because it should not exist anymore). And if I declare the Timer as a final variable in the Code outside so that I can do it, after canceling I cannot reuse it anymore. So how can I terminate that TimerTask but then still be able to use a Timer?
Android Timer is thread based from the Android Developers website:
http://developer.android.com/reference/java/util/Timer.html
When a timer is no longer needed, users should call cancel(), which releases the timer's thread and other resources. Timers not explicitly cancelled may hold resources indefinitely.
I would recommend instantiating the timer inside the onclicklistener only i.e. something similar to this:
/*Code outside*/
Timer t = null;
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(t == null)
t = new Timer();
else
t.cancel();
t.scheduleAtFixedRate(
new TimerTask(){
public void run(){
stuffToBeDone();
}
},someVariableDelay,someVariablePeriod);
}
}

Application hangs when Timer is turn off/on frequently

I have Multi-Shot facility in my camera application. I am using following short of code to do that.
if (TIMER_STARTED) {
multishotTimer.cancel();
multishotTimer.purge();
multishotTimer = null;
TIMER_STARTED = false;
} else {
multishotTimer = new Timer();
multishotTimer.schedule(new TimerTask() {
#Override
public void run() {
TIMER_STARTED = true;
Camera camera = surfaceView.getCamera();
camera.takePicture(null, null,
new HandlePictureStorage());
}
}, 1000, 5000L);
}
Here, TIMER_STARTED is boolean flag which indicate whether timer is started or not. HandlePictureStorage is class which handles PictureCallback.
Question:
When first time i click on "MultiShot" button, it will start timer and take picture every 5 seconds. To stop timer, I one more time click on same button. But if I continuously clicking on button, application hangs and force stopped. Then after I need to switch off my device due to camera is used by stopped service and can't release it lightly. How can I manage start and stop timer?
You don't need TIMER_STARTED to choose whether the button will start or stop the multishot: you can simply check if (multishotTimer != null).
But even after this fix, clicking too fast may be dangerous: you should not create a new Timer between takePicture and HandlePictureStorage.
private bool isCapturing = false;
#Override
public void onClick(View v) {
if (multishotTimer != null) {
multishotTimer.cancel();
multishotTimer.purge();
multishotTimer = null;
}
else if (!isCaptureing) {
multishotTimer = new Timer();
multishotTimer.schedule(new TimerTask() {
#Override
public void run() {
isCapturing = true;
Camera camera = surfaceView.getCamera();
camera.takePicture(null, null,
new HandlePictureStorage());
}
}, 1000, 5000L);
}
}
class HandlePictureStorage implements ... {
#Override
public void onPictureTaken(...) {
isCaptureing = false;
}
}
You need to move TIMER_STARTED = true; from the timer task to the else part, for example after scheduling the timer.
To improve the performance, you should create a TimerTask field instead of recreating an anonymous class every time you create and start the timer.

Twice call of timer crashes my app: Android

I'm trying to develop a small android App. In that app I need to use Timer control, which will be fired at button click. What problem I'm getting is, First timer task call is working fine but when I'm calling it again my app getting crashes. Code using for timer task is:
Timer timer = new Timer();
TimerTask refreshRam;
final Handler handler = new Handler();
refreshRam = new TimerTask()
{
public void run()
{
handler.post(new Runnable()
{
public void run()
{
txtFreeRam.setText(String.valueOf(getFreeRam()).toString());
}
});
}};
}
timer.schedule(refreshRam, 400);
I want to call my timer task only when I'm clicking on a button. It shouldn't be repeated...
Thanks
Use timer.scheduleatfixedrate instead of schedule
timer.scheduleAtFixedRate(refreshRam,400, 5000);
When you reschedule a Timer, it throws:
java.lang.IllegalStateException: TimerTask is scheduled already
It seems that you can only use a timer for once.
In order to reschedule a Timer, you need to simply create a new instance of it, each time. like the following:
.
.
.
//first time; works fine!
timer = new Timer();
refreshRam = new TimerTask() { ... }
timer.schedule(refreshRam, 400);
//second time; also works fine!
//be sure to terminate the timer task that is running by calling timer.cancel()
timer.cancel();
timer = new Timer();
refreshRam = new TimerTask() { ... }
timer.schedule(refreshRam, 400);

How can I create timer tick in Android?

I have this method
public void GetSMS(){
//in this method I read SMS in my app inbox,
//If have new SMS create notification
}
for this I think create timer tick method and every 5 sec call GetSMS()
How can I create a correct method for that ?
Here is an example of Timer and Timer Task. Hope this helps.
final Handler handler = new Handler();
Timer timer = new Timer(false);
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
// Do whatever you want
}
});
}
};
timer.schedule(timerTask, 1000); // 1000 = 1 second.
Maybe with a timer and a timertask?
See javadocs:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html
Yet receiving broadcasts is probably a more solid solution.
See: Android - SMS Broadcast receiver
Use Timer.scheduleAtFixedRate() as follow:
final Handler handler = new Handler();
Timer timer = new Timer(false);
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
GetSMS();
}
});
}
};
timer.scheduleAtFixedRate(timerTask, 5000, 5000); // every 5 seconds.
I saw it by accident.. This is not the right way to do it..
You don't need to check if there is a sms that received. Android provide broadcast receiver to get notified when sms is income.
Here you go, you have the link here.. Copy paste and it will work great
http://androidexample.com/Incomming_SMS_Broadcast_Receiver_-_Android_Example/index.php?view=article_discription&aid=62&aaid=87
Hope that this make sense
Although the above timer methods are the correct way to use timers of the sort you are after, I quite like this little hack:
new CountDownTimer(Long.MAX_VALUE, 5000)
{
public void onTick(long millisUntilFinished)
{
// do something every 5 seconds...
}
public void onFinish()
{
// finish off when we're all dead !
}
}.start();
Long.MAX_VALUE has, according the Java docs, a (signed) value of 2^63-1, which is around 292471 millennia ! So starting up one of these countdown timers effectively lasts forever relatively speaking. Of course this depends on your interval time. If you want a timer every 1 second the timer would "only" last 58494 millenia, but we don't need to worry about that in the grander scheme of things.

Android TimerTask crashes when called twice

I'm calling my TimerTask (m_timer) upon a button click:
m_timer.schedule(m_progressUpdater, 0, 500);
Which kicks off my run method:
#Override
public void run() {
//do some stuff
progressBar.setProgress(currentProgress);
if (progress >= 100) {
handler.post(new Runnable() {
#Override
public void run() {
CompleteTask();
}
});
}
}
I can call this once and it works perfectly. When I call it again, my app stops responding. I'm thinking that I need to cancel the task in my CompleteTask() method, but I've tried cancelling both the TimerTask and the Timer, and it still crashes. Anyone know what the problem might be?
Have you tried creating new TimerTask instance for the second call? And by the way, don't cancel the timer otherwise it will cancel all of its task. And what did the log say?
When you reschedule a Timer, it throws:
java.lang.IllegalStateException: TimerTask is scheduled already
It seems that you can only use a timer for once.
In order to reschedule a Timer, you need to simply create a new instance of it, each time. like the following:
// if you have already started a TimerTask,
// you must(?) terminate the timer before rescheduling it again.
if(m_timer != null)
m_timer.cancel();
m_timer = new Timer();
m_progressUpdater = new myTimerTask();
m_timer.schedule(m_progressUpdater, 0, 500);

Categories

Resources