I am trying to stop a Timer or TimerTask, but the method doesn't destroy the task...
First the code how i set up the timertask:
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
load_unread();
Log.d("TIMER", "Timer set off");
}
});
}};
t=new Timer();
t.schedule(scanTask, 300, 10000);
and now I'm trying to "kill" this Task at onDestroy:
#Override
protected void onDestroy() {
super.onDestroy();
scanTask.cancel();
t.cancel();
t.purge();
handler.removeCallbacksAndMessages(null);
System.out.println("Chat destroyed");
}
but this doesn't work? Can you please help me finding a solution?
Thanks!
EDIT: I finally found the answer. Don't know why mine didn't work...
Here the code for everyone who has the same Problem. I think this is a better and more efficient solution anyway:
private Handler handler = new Handler();
runnable.run();
private Runnable runnable = new Runnable()
{
public void run()
{
//
// Do the stuff
//
handler.postDelayed(this, 1000);
}
};
and to stop:
handler.removeCallbacks(runnable);
taken from here:
https://stackoverflow.com/a/11640073/1956197
After looking at your edit, the only thing I'd suggest is to use handler.post(runnable); instead of runnable.run(); This way you are always executing your runnable on a separate thread. Otherwise, your first execution will run on the main thread, then future executions run inside the handler on a separate thread.
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
//
// Do the stuff
//
handler.postDelayed(this, 1000);
}
};
handler.post(runnable);
Cancel the TimerTask before setting it to null.
scanTask.cancel();
this example start the timer unitl destroyed
private lateinit var timerTask: TimerTask
timerTask = object : TimerTask() {
override fun run() {
Log.d("KTZ", "$minutes:$seconds");
timeRecordingLiveData.postValue("$minutes:$seconds")
seconds += 1;
if (seconds == 60) {
Log.d("KTZ", "$minutes:$seconds");
timeRecordingLiveData.postValue("$minutes:$seconds")
seconds = 0;
minutes += 1;
}
}
}
Cancel the timertask in onDestroy()
timerTask.cancel()
Related
UPDATE : The code is working only that I dint init the textview, but this question is answered so I cant remove it either. So I will leave this question as it is for anyone trying to implement a Timertask with handler that makes use of Looper.getMainLooper that directly attaches it to the UI THREAD.
OLD QUERY :Hello guys I am trying to implement a timer that runs a task which has a handler.
I am using it to update the UI every second.
This is what I am implementing:
private void setRepeatingAsyncTask() {
handler = new Handler(Looper.getMainLooper());
timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
i++;
tview.setText(String.valueOf(i));
} catch (Exception e) {
// error, do something
}
}
});
}
};
timer.schedule(task, 0, 1000); // interval of one minute
}
when I make setRepeatingAsyncTask() on create or somewhere else like button clicklistner, etc either the timer or the handler is not starting.
Please help new to android!
I used Handler to process the task every 1 sec, Using just Handler:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//some task
handler.postDelayed(this, 1000); //looping is every 1 secs
}
}, 0); //initial delay of 0
I have tried multiple ways to have a single persistent timer update the ui in multiple activities, and nothing seems to work. I have tried an AsyncTask, a Handler, and a CountDownTimer. The code below does not execute the first Log.i statement.... Is there a better way to start the timer (which must be called from another class) in Main (which is the only persistent class)?
public static void MainLawTimer()
{
MainActivity.lawTimer = new CountDownTimer(MainActivity.timeLeft, 1000)
{
public void onTick(long millisUntilFinished)
{
Log.i("aaa","Timer running. Time left: "+MainActivity.timeLeft);
MainActivity.timeLeft--;
if(MainActivity.timeLeft<=0)
{
//do stuff
}
else
{
//call method in another class
}
}
public void onFinish()
{ }
}.start();
}
To clarify my problem:
When I run the code the Log.i("aaa","Timer running") statement is never shown in the log, and the CountDownTimer never seems to start. MainLawTimer is called from another class only (not within the same class.
For CountDownTimer
http://developer.android.com/reference/android/os/CountDownTimer.html
You can use a Handler
Handler m_handler;
Runnable m_handlerTask ;
int timeleft=100;
m_handler = new Handler();
#Override
public void run() {
if(timeleft>=0)
{
// do stuff
Log.i("timeleft",""+timeleft);
timeleft--;
}
else
{
m_handler.removeCallbacks(m_handlerTask); // cancel run
}
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run();
Timer
int timeleft=100;
Timer _t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
Log.i("timeleft",""+timeleft);
//update ui
}
});
if(timeleft>==0)
{
timeleft--;
}
else
{
_t.cancel();
}
}
}, 1000, 1000 );
You can use a AsyncTask or a Timer or a CountDownTimer.
Thank you all for your help, I discovered the error in my code... timeLeft was in seconds rather then milliseconds. Since timeLeft was under 1000 (the wait period) the timer never started.
THE PROBLEM
I am having problems stopping the Timer whilst developing in android.
The timer is already null when it comes to stopping it.
I then move the timer initialisation to outside of a method just like the TimerTask which solves the null problem but still doesn't cancel when timer.cancel(); is called upon it.
The code below is an example of the timer already being null when it comes to stopping the recording.
TimerTask
My TimerTask is initialized inside the class but outside of a method and the codes below...
private TimerTask task = new TimerTask() {
#Override
public void run() {
Log.e("TRACK_RECORDING_SERVICE","Timer Running");
}
};
Timer & Timer Start
I then have a startRecroding method which is called when I want to start the timer...
public void startRecording(){
timer = new Timer("Message Timer");
timer.scheduleAtFixedRate(this.task, 0, 1000);
}
Timer Stop
I then call the below method when I want to stop the timer...
public void stopRecording() {
if (timer != null) {
timer.cancel();
timer = null;
} else {
Log.e("TRACK_RECORDING_SERVICE","Timer already null.");
}
}
Any help would be much appreciated.
timer = new Timer("Message Timer");
Here your object timer is not a static so timer.cancel(); will cancel another instance of the Timer class. I suggest you to create a static instance variable of Timer Class on the top of the class, like below,
private static Timer timer;
in the run() method, check if timer is null then
private TimerTask task = new TimerTask() {
#Override
public void run() {
if (timer == null)
cancel();
...
}
cancel the operation.
Ok so the problem was in the instantiation not the actual stopping of the timer.
Everytime I called:
timer = Timer()
timer!!.scheduleAtFixedRate(object : TimerTask() {
override fun run() {
//something
}
}, delay, period)
It created another instance so the old instance was still running somewhere with no way to stop it.
So I just made sure to instantiate it when the timer is null so that no previous instance is getting pushed around and still running on the background.
if(timer == null) {
timer = Timer()
timer!!.scheduleAtFixedRate(object : TimerTask() {
override fun run() {
// something
}
}, delay, period)
}
Then just cancel it and set it to null.
fun stopTimer() {
if (timer != null) {
timer!!.cancel()
timer!!.purge()
timer = null
}
}
if(waitTimer != null) {
waitTimer.cancel();
waitTimer.purge()
waitTimer = null;
}
I know it's late but I also encountered this issue in my project, and hope my solution may give people some ideas. What I did in my project is as below:
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
//TODO Update UI
}
};
public void stopTimer() {
if (timer != null) {
handler.removeCallbacks(runnable);
timer.cancel();
timer.purge();
timer = null;
}
}
public startTimer() {
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(runnable);
}
}, 0, 100);
}
I think what's missed in previous answers is removeCallbacks.
Try this example....
TimerTask mTimerTask;
final Handler handler = new Handler();
Timer t = new Timer();
int nCounter = 0;
//function for start timer
public void doTimerTask()
{
mTimerTask = new TimerTask()
{
public void run()
{
handler.post(new Runnable()
{
public void run()
{
nCounter++:
//your code
.....
......
}
});
}};
// public void schedule (TimerTask task, long delay, long period)
t.schedule(mTimerTask,0,50); //
}
//function for stop timer
public void stopTimerTask(){
if(mTimerTask!=null){
Log.d("TIMER", "timer canceled");
mTimerTask.cancel();
nCounter = 0;
}
}
//use above two function for start and stop timer.
Just in case if someone still comes here to find a solution to this problem, here is my experience.
I am running a timer in a service.
startForegroundService(mServiceIntent);
timer = new Timer();
When you refresh a service, you don't necessarily cancel it first, you just call startForegroundService(mServiceIntent); again.
If you don't cancel the timer before you refresh the service, the original timer is still running in the background and calling methods even though you stop the timer in the refreshed new service.
So to sum it up, stop your timer before you refresh or update a background task.
I hope it helps someone.
Though this is an old question, I've figured out an easy solution.
var timeTaskInstance : TimerTask ?= null
val task: TimerTask = object : TimerTask() {
override fun run() {
timeTaskInstance = this
Log.e("TRACK_RECORDING_SERVICE", "Timer Running")
}
}
Now cancel timer from anywhere:
timeTaskInstance?.cancel()
I think you've canceled another instance of the timer.
Your timer task would be better handled by a helper class.
public class TimerHelper {
Timer timer;
long InitialInMillis = 10 * 1000;
long DelayInMillis = 2 * 60 * 1000; // 2 minutes
public TimerHelper() {
timer = new Timer();
timer.schedule(new MyTimerTask(), InitialInMillis, DelayInMillis);
}
public void stopTimer() {
if(timer != null){
timer.cancel();
}
}
class MyTimerTask extends TimerTask {
#Override
public void run() {
// your task will be run every 2 minutes
yourTask();
}
}
}
I want to show a text view with elapsed seconds from 60 to 1.
How should I take handler event?
time = GetTime.Showtime();
elapsetime.setText(time + " Secs");
Use a CountDownTimer, http://developer.android.com/reference/android/os/CountDownTimer.html
First of all, you have to create and initialize Timer object:
Timer myTimer;
myTimer = new Timer();
After that you can call use the schedule method to call timerMethod() (or your method). It will the timerMethod() every second (1000 milliseconds).
myTimer.schedule(new TimerTask() {
#Override
public void run() {
timerMethod();
}
}, 0, 1000);
//Runs your doSomething() in the UI Thread
private void timerMethod()
{
this.runOnUiThread(doSomething);
}
// make your doSomething() runnable
private Runnable doSomething = new Runnable() {
public void run() {
// Your code for doing something
}
i use handler thread runnable.
handler =new Handler();
runnable = new Runnable() {
#Override
public void run() {
elapsetime.setText(time+" Secs");
time--;
if(time<1){
handler.removeCallbacks(runnable);
}else{
handler.postDelayed(this, 1000);
}
}
};
handler.postDelayed(runnable, 1000);
I developed an application to display some text at defined intervals in the Android emulator screen. I am using the Handler class. Here is a snippet from my code:
handler = new Handler();
Runnable r = new Runnable() {
public void run() {
tv.append("Hello World");
}
};
handler.postDelayed(r, 1000);
When I run this application the text is displayed only once. Why?
The simple fix to your example is :
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
tv.append("Hello World");
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
Or we can use normal thread for example (with original Runner) :
Thread thread = new Thread() {
#Override
public void run() {
try {
while(true) {
sleep(1000);
handler.post(this);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
You may consider your runnable object just as a command that can be sent to the message queue for execution, and handler as just a helper object used to send that command.
More details are here http://developer.android.com/reference/android/os/Handler.html
new Handler().postDelayed(new Runnable() {
public void run() {
// do something...
}
}, 100);
I think can improve first solution of Alex2k8 for update correct each second
1.Original code:
public void run() {
tv.append("Hello World");
handler.postDelayed(this, 1000);
}
2.Analysis
In above cost, assume tv.append("Hello Word") cost T milliseconds, after display 500 times delayed time is 500*T milliseconds
It will increase delayed when run long time
3. Solution
To avoid that Just change order of postDelayed(), to avoid delayed:
public void run() {
handler.postDelayed(this, 1000);
tv.append("Hello World");
}
For repeating task you can use
new Timer().scheduleAtFixedRate(task, runAfterADelayForFirstTime, repeaingTimeInterval);
call it like
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
}
},500,1000);
The above code will run first time after half second(500) and repeat itself after each second(1000)
Where
task being the method to be executed
after the time to initial execution
(interval the time for repeating the execution)
Secondly
And you can also use CountDownTimer if you want to execute a Task number of times.
new CountDownTimer(40000, 1000) { //40000 milli seconds is total time, 1000 milli seconds is time interval
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
}
}.start();
//Above codes run 40 times after each second
And you can also do it with runnable. create a runnable method like
Runnable runnable = new Runnable()
{
#Override
public void run()
{
}
};
And call it in both these ways
new Handler().postDelayed(runnable, 500 );//where 500 is delayMillis // to work on mainThread
OR
new Thread(runnable).start();//to work in Background
I believe for this typical case, i.e. to run something with a fixed interval, Timer is more appropriate. Here is a simple example:
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
// If you want to modify a view in your Activity
MyActivity.this.runOnUiThread(new Runnable()
public void run(){
tv.append("Hello World");
});
}
}, 1000, 1000); // initial delay 1 second, interval 1 second
Using Timer has few advantages:
Initial delay and the interval can be easily specified in the schedule function arguments
The timer can be stopped by simply calling myTimer.cancel()
If you want to have only one thread running, remember to call myTimer.cancel() before scheduling a new one (if myTimer is not null)
Handler handler=new Handler();
Runnable r = new Runnable(){
public void run() {
tv.append("Hello World");
handler.postDelayed(r, 1000);
}
};
handler.post(r);
Kotlin
private lateinit var runnable: Runnable
override fun onCreate(savedInstanceState: Bundle?) {
val handler = Handler()
runnable = Runnable {
// do your work
handler.postDelayed(runnable, 2000)
}
handler.postDelayed(runnable, 2000)
}
Java
Runnable runnable;
Handler handler;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
// do your work
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
If I understand correctly the documentation of Handler.post() method:
Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
So examples provided by #alex2k8, even though are working correctly, are not the same.
In case, where Handler.post() is used, no new threads are created. You just post Runnable to the thread with Handler to be executed by EDT.
After that, EDT only executes Runnable.run(), nothing else.
Remember:
Runnable != Thread.
Kotlin with Coroutines
In Kotlin, using coroutines you can do the following:
CoroutineScope(Dispatchers.Main).launch { // Main, because UI is changed
ticker(delayMillis = 1000, initialDelayMillis = 1000).consumeEach {
tv.append("Hello World")
}
}
Try it out here!
An interesting example is you can continuously see a counter/stop-watch running in separate thread. Also showing GPS-Location. While main activity User Interface Thread is already there.
Excerpt:
try {
cnt++; scnt++;
now=System.currentTimeMillis();
r=rand.nextInt(6); r++;
loc=lm.getLastKnownLocation(best);
if(loc!=null) {
lat=loc.getLatitude();
lng=loc.getLongitude();
}
Thread.sleep(100);
handler.sendMessage(handler.obtainMessage());
} catch (InterruptedException e) {
Toast.makeText(this, "Error="+e.toString(), Toast.LENGTH_LONG).show();
}
To look at code see here:
Thread example displaying GPS Location and Current Time runnable alongside main-activity's User Interface Thread
now in Kotlin you can run threads this way:
class SimpleRunnable: Runnable {
public override fun run() {
println("${Thread.currentThread()} has run.")
}
}
fun main(args: Array<String>) {
val thread = SimpleThread()
thread.start() // Will output: Thread[Thread-0,5,main] has run.
val runnable = SimpleRunnable()
val thread1 = Thread(runnable)
thread1.start() // Will output: Thread[Thread-1,5,main] has run
}