android - 使用持续执行的 TimerTask 优化服务运行

标签 android service timer timertask

我需要一个应该一直运行的服务,直到它被我的 Activity 明确停止,并且即使它由于某些问题而停止(START_STICKY 标志)也应该重新启动。此服务应使用 TimerTask 连续执行某些操作(每隔几秒)。我最终得到了以下代码。

public class SomeService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    TimerTask timerTask;
    final Handler handler = new Handler();
    Timer timer = new Timer();

    @Override
    public void onCreate() {
        // code to execute when the service is first created
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        // code to execute when the service is shutting down
        super.onDestroy();
    }

    @Override
    public void onStart(Intent intent, int startid) {
        // code to execute when the service is starting up
        timerTask = new TimerTask() {
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                                   //KEEP RUNNING SOME ERRANDS HERE
                        }
                    }
                });
            }
        };
        timer.scheduleAtFixedRate(timerTask, 100L, 1700L);
    }

}

无论如何我可以优化它以连续运行吗?

最佳答案

每秒运行一次听起来很过分,但是您有什么理由不使用 AlarmManager 来触发 IntentService 吗?然后系统将负责可靠地触发您的服务。你是否能实现可靠的 1 秒重新触发,我不知道。由于马克在另一个答案中提到的原因,这似乎是个坏主意。

关于android - 使用持续执行的 TimerTask 优化服务运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7436649/

相关文章:

android - Android中位置服务和Activity之间的通信?

vb.net - 如何定期更改背景图片

c# - 如果计时器运行时间超过计时器间隔,计时器将终止任务/作业

go - 如何在 context.WithDeadline 或简单计时器之间做出决定?

android - React-Native:FlatList 中的反向 zIndex

c# - Xamarin - 在没有硬件加速支持的笔记本电脑上部署

android - 在实际设备中安装 .apk 文件仅用于测试

service - 如何将 keycloak 安装为服务,使其自动启动?

android - startForeground() 不显示我的通知

android-actionbar - Android ActionBar 可以放在底部吗?