Timer inside Android service

微笑、不失礼 提交于 2019-12-12 20:23:54

问题


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;
}

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?


回答1:


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;
}

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



来源:https://stackoverflow.com/questions/38265993/timer-inside-android-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!