Reputation: 488
I have a function that gets executed every 0.~2 seconds (due to lag). However, I would like to perform a toast every 5 seconds. May i know how I can achieve this ?
public void navigation(Coordinate userPosition , Coordinate destination){
if (Math.abs(userPosition.y - destination.y) > 500) {
{Toast.makeText(this, "Walk for " + Math.abs(CheckPoint.y - UserPosition.y) + "mm", Toast.LENGTH_SHORT).show(); }
}
Above is a sample of my current code. The frequency of which the toast gets executed is dependent on the current 'lag'. I would like the toast to be sent every 5 seconds minimum.
Upvotes: 0
Views: 1930
Reputation: 1568
try this for exactly five second,
int count = 100; //Declare as inatance variable
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
final Toast toast = Toast.makeText(
getApplicationContext(), --count + "",
Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toast.cancel();
}
}, 5000);
}
});
}
}, 0, 5000);
Upvotes: 1
Reputation: 1097
You can do it this way:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
navigation(...);
handler.postDelayed(this, 5000);
}
}, 5000);
Upvotes: 2
Reputation: 1073
Maybe with a loop Thread
? Try it out:
private Thread loopThread = new Thread(new Runnable() {
public void run() {
while(true){
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(this, "Your text!", Toast.LENGTH_SHORT).show();
});
Thread.Sleep(5000); //Wait 5 seconds, then repeat!
}catch (Exception e) {
return;
}catch (InterruptedException i) {
return;
}
}
}
});
Then start the Thread
wherever you want like:
Thread myThread = new Thread(loopThread);
myThread.start();
And stop it with:
myThread.interrupt();
Hope it helps!
Upvotes: 0
Reputation: 18765
Create a Thread and loop that thread
Thread myThread = null;
Runnable runnable = new CountDownRunner();
myThread = new Thread( runnable );
myThread.start();
class CountDownRunner implements Runnable
{
// @Override
public void run()
{
while( !Thread.currentThread().isInterrupted() )
{
try
{
navigation(); // do the work here
Thread.sleep( 2000 ); // time interval for the counter. it will run every 2 sec
}
catch( InterruptedException e )
{
Thread.currentThread().interrupt();
}
catch( Exception e )
{
}
}
}
}
public void navigation(Coordinate userPosition , Coordinate destination){
if (Math.abs(userPosition.y - destination.y) > 500) {
{Toast.makeText(this, "Walk for " + Math.abs(CheckPoint.y - UserPosition.y) + "mm", Toast.LENGTH_SHORT).show(); }
}
Upvotes: 0