I have a problem implementing what should be a simple example with services.
Following the Android developer scheme I managed to Bind to a service. The service works perfectly.
What i want to implement is the starting Date of the Service. I have in the
public class MyService extends Service {
private Date _firstActivation= new Date();
....
....
public Date GetFirstActivation() {
return _firstActivation;
}
}
In the main activity that binds to the service I have a basic implementation during the OnStart method
// 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");
}
where _myService is the MyService and mConnection is the ServiceConnection…
Now what i expect is that once the service has started the first time, each time i Stop the activity (and at the same time unbind) and restart the activity (and at the same time bind) on the textview I can see always the same starting time.
What happens in that the time changes everytime i restart the activity…
Does anyone has a clue?
The lifecycle of the
Serviceis determined:– if is started via
bindService, theServiceis stopped when unbinding– if started via
startService, it is stopped viastopServiceor if Android OS wants thisSo first of all: always start your service via
startServiceand then bind to it.In your bind you can do:
_startingTime_TV.setText(_df.format(_myService.GetFirstActivation()));Because after
bindService(intent, mConnection, 0);you are not bound yet. You have to wait for a callback:onServiceConnected(function ofServiceConnection)