Android 如何每 10 秒调用一次函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21553830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:44:53  来源:igfitidea点击:

how can I call function every 10 sec?

androidandroid-handler

提问by user3257386

I want make an app that call a function for example every 10 sec.

我想制作一个应用程序,例如每 10 秒调用一次函数。

I wrote my code like this:

我这样写我的代码:

Handler ha=new Handler();
ha.postDelayed(new Runnable() {
    @Override
    public void run() {
        //call function

    }
}, 10000); 

But my function call just one time in 10 sec after compile this code.

但是我的函数在编译这段代码后的 10 秒内只调用了一次。

How can I fix it?

我该如何解决?

回答by Rudi

Do it like this:

像这样做:

final Handler ha=new Handler();
ha.postDelayed(new Runnable() {

    @Override
    public void run() {
        //call function

        ha.postDelayed(this, 10000);
    }
}, 10000);

回答by FD_

Use a combination of Timerand TimerTasklike this:

使用TimerTimerTask像这样的组合:

int delay = 0; // delay for 0 sec. 
int period = 10000; // repeat every 10 sec. 
Timer timer = new Timer(); 
timer.scheduleAtFixedRate(new TimerTask() 
{ 
    public void run() 
    { 
        //Call function
    } 
}, delay, period); 

Also make sure to use runOnUiThread()if you want to modify the UI.

runOnUiThread()如果要修改 UI,请确保使用。

回答by Amir Alagic

It looks that Timer and TimerTask are what are you looking for

看起来 Timer 和 TimerTask 正是你要找的

Timer timer = new Timer();

TimerTask timerTask = new TimerTask() {       
    @Override
     public void run() {
         //your code
     });
}
    };

timer.schedule(timerTask, 0, 10000);

回答by Sepehr

You can use Rx java& Rx Androidby adding this dependency as below :

您可以通过添加此依赖项来使用Rx javaRx Android,如下所示:

//Rx Java
implementation 'io.reactivex.rxjava2:rxjava:2.2.13'

//Rx Android
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'

checkout Herefor the latest version.

在这里结帐以获取最新版本。

You need an Observable like this :

你需要一个像这样的 Observable :

private final Observable etaUpdateRepeatableObservable =
        Observable
                .interval(ETA_UPDATE_INTERVALS, TimeUnit.MINUTES)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .repeat();

just change ETA_UPDATE_INTERVALSto your specific value.

只需更改ETA_UPDATE_INTERVALS为您的特定值。

You need a Disposablefor subscribing to observable and to disposeit when required (Like onCleared()on ViewModels)

您需要一个Disposable来订阅 observable 并在需要时处理它(如ViewModels上的onCleared()

private Disposable etaUpdateDisposable;

You need a Consumerthat your repeated logic would go there.

你需要一个消费者,你的重复逻辑会去那里。

private final Consumer etaUpdateConsumer = o -> {
    //Here you got the repeated logic
};

Now you can subscribe(Start repeating function) and dispose(stop) observableevery time you need.

现在,您可以在每次需要时订阅(开始重复功能)和处置(停止) 可观察对象

  private void addEtaUpdateDisposable() {
    if (etaUpdateDisposable == null) {
        etaUpdateDisposable = etaUpdateRepeatableObservable.subscribe(etaUpdateConsumer);
    }
}

private void disposeEtaUpdate() {
    if (
            etaUpdateDisposable != null &&
                    !etaUpdateDisposable.isDisposed()
    ) {
        etaUpdateDisposable.dispose();
        etaUpdateDisposable = null;
    }
}

回答by InnocentKiller

Use below code.

使用下面的代码。

Timer myTimer = new Timer();
            myTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //your function
                }
            }, 10000);

回答by Cheerag

There are number of alternative ways to do this. Personally, I prefer to use ScheduledExecutorService:

有许多替代方法可以做到这一点。就个人而言,我更喜欢使用 ScheduledExecutorService: