Android服务中的计时器 [英] Timer inside Android service

查看:269
本文介绍了Android服务中的计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Android服务,该服务会启动一个执行以下操作的计时器:

I have an Android service that starts a timer that does stuff:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    timer.scheduleAtFixedRate(new VeryImportantTask(), 0, RATE);
    return START_STICKY;
}

我知道服务是单例的,但是每次调用startService()时都会调用onStartCommand方法吗?如果是这样,我应该控制我的计时器是第一次启动,不是吗?我在考虑服务中的静态布尔值标志.有更好的方法吗?

I know Services are singleton but, does onStartCommand method called each time that I call startService()? If so, I should control that my timer is just started the first time, shouldn't I? I'm thinking in a static boolean flag in the service. Is there a better way?

推荐答案

在您的情况下,即 START_STICKY ,您只需检查意图值 nullity 像这样

In your case i.e START_STICKY you can simply check the intent value nullity like this

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
      if(null==intent){
              // service restarted do what you want
        }
    return START_STICKY;
}

因为初次使用意图不会为 null ,并且每次使用START_STICKY重新启动时,意图都将为 null .

because first time the intent will not be null and it will be null every time in case of a restart with START_STICKY.

这篇关于Android服务中的计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆