我在实现一个简单的服务示例时遇到问题。 按照 Android 开发人员方案,我成功绑定(bind)到服务。该服务运行完美。
我想要实现的是服务的开始日期。我在
public class MyService extends Service {
private Date _firstActivation= new Date();
....
....
public Date GetFirstActivation() {
return _firstActivation;
}
}
在绑定(bind)到服务的主要 Activity 中,我在 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 上停止 Activity (并同时取消绑定(bind))并重新启动 Activity (并同时绑定(bind))时,我都可以看到始终相同的开始时间。
每次我重新启动 Activity 时时间都会发生变化...
有人知道吗?
最佳答案
Service
的生命周期确定为:
- 如果通过bindService
启动,则在解除绑定(bind)时停止Service
- 如果通过 startService
启动,则通过 stopService
停止,或者如果 Android 操作系统需要这样
所以首先:始终通过 startService
启动您的服务,然后绑定(bind)到它。
在您的绑定(bind)中,您可以执行以下操作: _startingTime_TV.setText(_df.format(_myService.GetFirstActivation()));
因为在 bindService(intent, mConnection, 0);
之后,您还没有绑定(bind)。您必须等待回调:onServiceConnected
(ServiceConnection
的函数)
关于安卓服务启动时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13012693/