2

我在实现应该是一个简单的服务示例时遇到问题。按照 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 上重新启动活动(同时绑定)我可以看到总是相同的起始时间。

每次我重新开始活动时,时间都会发生变化......

有人有线索吗?

4

1 回答 1

2

的生命周期Service是确定的: - 如果通过 启动bindServiceService则在解除绑定时停止 - 如果通过 启动startService,则通过stopService或者如果 Android OS需要它则停止

所以首先:总是通过启动你的服务startService,然后绑定到它。在你的绑定中,你可以这样做:_startingTime_TV.setText(_df.format(_myService.GetFirstActivation())); 因为在bindService(intent, mConnection, 0);你还没有被绑定之后。您必须等待回调:(onServiceConnected函数ServiceConnection

于 2012-10-22T14:15:46.753 回答