如何在服务中调用Timer

时间:2016-08-18 15:20:50

标签: android android-layout android-fragments countdowntimer

我有一个countdown timer,从用户Logged In开始。 10分钟后,Logged Out用户。

它工作正常,但如果用户停止应用程序,则计时器停止工作,用户永远是logged in

所以我把这整件事都放在一个服务中,这样它就会起作用,或者用户停止应用程序。

问题是,在Countdown Timer中添加Service后,这已停止工作。我已在debug mode上进行了检查,但未进入service - onCreate方法。

这就是我打电话给服务的方式。

 startService(new Intent(this,LogoutService.class));

我的服务类,调用CountdownTimer Class,首先这段代码写在我现在写startService()的地方

public class LogoutService extends Service {

    @Override
    public void onCreate() {
        UserLoggedInTimer logoutTimer= new UserLoggedInTimer(60000,1000);
        logoutTimer.setContext(getApplicationContext());
        logoutTimer.start();
    }

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

当我在没有服务的情况下调用它时倒数计时器工作得非常好,但是这里它只是没有进入服务,我希望它能正常工作,一旦我的应用程序成功启动上述服务。

1 个答案:

答案 0 :(得分:1)

将其放入onStartCommand()并将其返回START_STICKY

参考this