简体   繁体   English

`android.os.Handler.postDelayed` 会失败吗?

[英]Can `android.os.Handler.postDelayed` fail?

I would like to run a function periodically every 5 seconds in a foreground service.我想在前台服务中每 5 秒定期运行一个函数。 I use android.os.Handler.postDelayed for that, like this:我为此使用android.os.Handler.postDelayed ,如下所示:

private Handler handler = new Handler();
private Runnable updater = new Runnable() {
    @Override
    public void run() {

        // Do some work

        scheduleTask();
    }
};

private void scheduleTask() {
    handler.postDelayed(updater, 5000);
}

@Override
public void onCreate() {
    super.onCreate();

    scheduleTask();
}

@Override
public void onDestroy() {
    super.onDestroy();

    handler.removeCallbacks(updater);
}

Is it possible for the handler.postDelayed to fail? handler.postDelayed是否有可能失败? Can the OS just cancel the delayed request?操作系统可以取消延迟的请求吗? How to catch that?怎么抓? I need this to run stable for days.我需要这个来稳定运行几天。

If the app is in the foreground then there is no chance that the handler gets cancelled.如果应用程序在前台,则处理程序不可能被取消。 It only gets cancelled when the app is running in background for some time or the Main thread has been destroyed.只有当应用程序在后台运行一段时间或主线程被破坏时,它才会被取消。

For reference you can read the android developers documentation https://developer.android.com/reference/android/os/Handler作为参考,您可以阅读 android 开发人员文档https://developer.android.com/reference/android/os/Handler

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM