I have been doing some research on this but found no clear answer.
The functional challenge is:
a) Start an activity with a layout (OK)
b) By Button (labeled START) click ist starts a background service (OK)
c) While the activity can be closed, the background service must continue to run (OK)
d) The background process is still there, I can see it in my notification (OK)
e) The activity restarts from the notification (OK)
f) The activity must connect to the process and get the status of it back. Simply checking if the service is running and set the label of the start-stop-button from (b) to STOP.
e) Hitting the button will stop the service, so that works.
Here are some details:
The connection to my service LogoTimerService is done in the activity like this:
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get
// LocalService instance
LogoTimerServiceBinder binder = (LogoTimerServiceBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
ON RESUME I call this function to actually connect:
private void connectLogoTimerService() {
Log.i(tag, "-connecting service");
Intent intent = new Intent(this, LogoTimerService.class);
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
if (mService!=null)
Log.i(tag, "-SERVICE BOUND");
else
Log.i(tag, "-Service NOT bound");
}
When I start the application the first time, I get a the second (NOT bound) message.
Why is it not bound? Is it to slow? (It seems like it playing around.)
If I do not destroy the activity the mService is found.
How can I synchronize this, so I can get the status back?
I start AND bind the service. Is this correct?
I can see that the service is running using this code (I found it on this site, thanks):
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
if (LogoTimerService.class.getName().equals(
service.service.getClassName())) {
return true;
}
}
return false;
}
Thank you very much for your help!
Answer on your first question is because the bindService is ‘async’. You will enter the if statement before onServiceConnected is called.