Android - Run a thread repeatingly within a timer
Just simply use below snippet
private final Handler handler = new Handler();
private Runnable runnable = new Runnable() {
public void run() {
//
// Do the stuff
//
handler.postDelayed(this, 1000);
}
};
runnable.run();
To stop it use
handler.removeCallbacks(runnable);
Should do the trick.
How to stop the Timer thread?
Given that Thread.stop is deprecated, the only option you have is to add some signalling of your own, like a boolean variable that you set when you want it to stop.
e.g.
boolean stop = false;
public void startTimer() {
startTime = System.currentTimeMillis();
final Handler handler = new Handler();
task =new Thread() {
@Override
public void run() {
if (stop) {
return;
}
long millis = System.currentTimeMillis()-startTime;
long secs = millis / 1000 % 60; // seconds, 0 - 59
long mins = millis / 1000 / 60 % 60; // total seconds / 60, 0 - 59
long hours = millis / 1000 / 60 / 60; // total seconds / 3600, 0 - limitless
timeString = String.format("%02d:%02d:%02d", hours, mins, secs);
runOnUiThread(new Runnable() {
@Override
public void run() {
mtvtimer.setText(timeString);
}
});
handler.postDelayed(task, 1000);
}
And from somewhere else, you set stop = true
to stop it.
(this is a rough example code, just to get the idea through)
Android Timer instead of Thread.sleep for sending binary code via LED
Thread.sleep caused your current Thread to sleep at least 100ms. This doesn't mean that in 100 ms your next statement will be executed. Timer uses another thread, so if you need to perform some action on UI thread, you have to post the message to UI thread. If you need delayed message without blocking the UI thread - use Handler.post message:
Handler handler = new Handler();
try {
for (int a = 1; a <= 3; a++) {
for (int i = 0; i < data.length(); i++) {
if (data.charAt(i) == '1') {
handler.postDelayed(new Runnable() {
@Override public void run() {
camera.setParameters(parametersOn);
camera.startPreview();
}
}, i * 100);
} else {
handler.postDelayed(new Runnable() {
@Override public void run() {
camera.setParameters(parametersOff);
camera.startPreview();
}
}, i * 100);
}
}
}
} catch (Exception e) {
}
Having A Timer Use The Main Thread in Kotlin
You can extend timerTask to return on the main thread.
Basically, get a Hander that runs on the main thread:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
public void run() {
// UI code goes here
}
});
Then have timerTask execute its function parameter in the run method above. Alternatively, you can just have that code in you lambda or even use activity.runOnUiThread()
. Really the correct solution comes down to how often you do this in your code, of it's a one off just use runOnUiThread
.
Android how to run thread for each 25 ms?
Use a ScheduledExecutorService
:
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(/* Your Runnable */, 0, 25, TimeUnit.MILLISECONDS);
Or RxJava:
Flowable.interval(0, 25, TimeUnit.MILLISECONDS).subscribe(/* Code to execute */);
Android CountDownTimer Class Lagging Main Thread
I decided to take a different approach which has served my purposes very well. No lag or thread issues and can easily be restarted over and over. Hope this helps someone out.
int startCountdown = 5;
int currentCountdown;
Handler countdownHandler = new Handler();
Timer countdownTimer = new Timer();
public void startCountdownTimer() {
currentCountdown = startCountdown;
for (int i = 0; i <= startCountdown; i++) {
TimerTask task = new TimerTask() {
@Override
public void run() {
countdownHandler.post(doA);
}
};
countdownTimer.schedule(task, i * 1000);
}
}
final Runnable doA = new Runnable() {
@Override
public void run() {
if (currentCountdown != 0) {
tvTextView.setText("" + currentCountdown);
currentCountdown--;
} else {
currentCountdown = startCountdown;
startCountdownTimer();
}
}
};
Related Topics
Compound Class Names Are Not Supported Error in Webdriver
Any Good Orm Tools for Android Development
Sqlite in Android How to Update a Specific Row
How to Open a Command Terminal in Linux
Why Does Reading from Process' Inputstream Block Altough Data Is Available
Cannot Run Program "Mvn" Error=2, No Such File or Directory
Create a Shell Script to Run a Java Program on Linux
Synchronized Block on Grails Works on Windows But No in Linux
How to Fix Java.Awt.Headlessexception in Jenkins on Linux
Fill an Array With Random Numbers
Add Buttons to Tabs and Tab Area Javafx
How to Check If an App Running on Android
Getting Frames from Video Image in Android
How to Make This Jbutton Visible? When I Have Progressive Scan Background Jwindow()
Arval SQLexception: Fatal: Sorry, Too Many Clients Already in Postgres
Using Visualvm to Connect to a Remote Jstatd Instance Through a Firewall