2012-10-22 136 views
2

我有一个问题,实施什么应该是一个简单的例子与服务。 继Android开发人员计划后,我设法绑定到服务。该服务完美运作。android服务启动时间

我想实现的是服务的起始日期。我在

public class MyService extends Service { 

    private Date _firstActivation= new Date(); 
    .... 
    .... 
    public Date GetFirstActivation() { 
    return _firstActivation; 
} 
} 

在结合我OnStart方法中有一个基本实现服务的主要活动

// Check if the Service is running and if it's running let's bind to the service through ServiceConnectionClass 
    if (((MyApplication)getApplication())._serviceIsRunning) 
    { 
     Intent intent = new Intent(this, MyService.class); 
     bindService(intent, mConnection, 0); 
     _startingTime_TV.setText(_df.format(_myService.GetFirstActivation())); 
    } 
    else { 
     _startingTime_TV.setText("Service Not Started"); 
    } 

其中_myService是为MyService和mConnection是ServiceConnection ...

现在我期望的是,一旦服务第一次启动,每次我停止活动(同时解除绑定)并重新启动活动(并同时绑定)我可以看到的textview始终是相同的开始时间。

什么情况,该时间变化每次我重新启动活动...

没有人有线索?

回答

1

Service的生命周期决定: - 如果通过bindService启动,Service时解除绑定 停止 - 如果通过startService启动,它通过stopService或者Android操作系统停止想这

所以第一总是:始终通过startService开始您的服务,然后绑定到它。 在你的约束你可以这样做:_startingTime_TV.setText(_df.format(_myService.GetFirstActivation())); 因为在bindService(intent, mConnection, 0);之后,你还没有约束。你必须等待回调:onServiceConnected(功能ServiceConnection