我有一个每隔0.~2秒执行一次的功能(由于滞后)。但是,我想每隔5秒钟进行一次祝酒。我可以知道如何实现这一目标吗?
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(); }
}
以上是我当前代码的示例。吐司执行的频率取决于当前的延迟'。我希望最少每5秒发送一次吐司。
答案 0 :(得分:2)
你可以这样做:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
navigation(...);
handler.postDelayed(this, 5000);
}
}, 5000);
答案 1 :(得分:1)
试试这五秒钟,
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);
答案 2 :(得分:0)
创建一个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(); }
}
答案 3 :(得分:0)
也许有一个循环Thread
?试试吧:
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;
}
}
}
});
然后在任意位置启动Thread
:
Thread myThread = new Thread(loopThread);
myThread.start();
然后停止:
myThread.interrupt();
希望它有所帮助!