In my application i want to set a timeout when the user turn on 3G... after a certain amount of time elapsed , i will turn off 3G..
my problem is cancelling the scheduled timer.. every time i call timer.cancel() .. the program throws errors
the problem cause when i call clearTimeout() method..
Timer timer;
class RemindTask extends TimerTask {
public void run() {
//do something when time's up
log("timer","running the timertask..");//my custom log method
timer.cancel(); //Terminate the timer thread
}
}
public void setTimeout(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
public void clearTimeout(){
log("timer", "cancelling the timer task");//my custom log method
timer.cancel();
timer.purge();
}
please help me .. i am an android beginner..
Android has a class CountdownTimer which has start() and cancel().
Related
I have count down timer in a service.
When I stop the service, will the countdown timer still count? I mean will its onFinished method will be called even if the service has been stopped?
Countdown timer runs in a different thread and the callbacks are executed on the UI thread. Hence you need to manually cancel the timer whenever service is stopped. You can follow Hiren's answer.
private CountDownTimer mCountDownTimer;
on onCreate:
mCountDownTimer = new CountDownTimer(30000,1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
// Your stuff
}
};
mCountDownTimer.start();
on onDestroy:
#Override
protected void onDestroy() {
if(mCountDownTimer!=null){
mCountDownTimer.cancel();
}
super.onDestroy();
}
For stop service:
stopService(Your_Intent_For_Service);
Done
Yes, it would be called. You would end up leaking the service if the count down timer is not a static inner class
public void scheduleAtFixedRate (TimerTask task, long delay, long period). This looks promising but i have no idea how to use it. Any help would be appreciated.It was on android developer site.
Maybe this demo helps you:
import java.util.*;
public class TimerDemo {
public static void main(String[] args) {
TimerTask tasknew = new TimerScheduleFixedRateDelay();
Timer timer = new Timer();
timer.scheduleAtFixedRate(tasknew, 500, 1000);
}
public void run() {
System.out.println("working at fixed rate delay");
}
}
You need to have a method called "run" in your class, that will be repeately executed.
Source.
You can create a timer task and schedule it at a fixed rate like this:
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
// This method is called in a fixed interval
}
};
timer.scheduleAtFixedRate(task, delay, period);
If you need to interact with the UI in the TimerTask you should do it like this:
TimerTask task = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// Interact with UI here
}
});
}
};
public void scheduleAtFixedRate(TimerTask task,
long delay,
long period)
Android doc here.
Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
The task (TimerTask) is the code which will be executed forever, every period milliseconds. Delay is the time (in ms or Date if you want) which the Timer should wait until the start of the TimerTask.
You should remember Timer will run in a different thread from UI thread, so if you need to update the UI you should use runOnUiThread etc. (See Xaver Kapeller answer)
It could be an example
TimerTask tasknew = new TimerTask()
{
#Override
public void run()
{
/* Something here */
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(tasknew, 500, 1000);
I noticed here everyone just posted an example so it's just an extension with an explanation.
I'm trying to create a Timer that does something after 5 seconds.
Now in my main activity ( I only got 1 ) I wrote this class:
class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
textFeedback.setText("test");
timer.cancel();
}
}
}
In a function (and also in my mainactivity) I create a timer as new Reminder(5).
After 5 seconds the application crashes.
I don't see whats wrong, because I do it in normal java apps like this.
Not sure where you have initialized textFeedback.
textFeedback.setText("test"); cannot update ui from a timer task. Timer task runs on a non ui thread. Ui can be updated only on ui thread.
Your options use a Handler or runOnUiThread.
Note runOnUiThread is a method of Activity class. Requires Activity Context
More info
Android Thread for a timer
Thanks.
Solved it like this:
new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
//textFeedback.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
textFeedback.setText("");
}
}.start();
when the class Remainder is istatiate not know the var textFeedback , becaouse you nees to pass the owmer of the textFeedback
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);
HI!
I want make service in OnCreate(), and every five minute, the service show notification..
can you show me about it??
thanks before :)
You can use the TimerTask class with the postDelayed method.
private TimerTask mTask = new TimerTask() {
#Override
public void run() {
//Whatever you want
postDelayed(this, REPEAT_INTERVAL); // rinse and repeat...
}
};
And in your OnCreate launching the TimerTask for first time:
postDelayed(mTask, INITIAL_DELAY);
You can find some information in this android article
http://developer.android.com/resources/articles/timed-ui-updates.html