I have an activity which I use to launch a foreground service which continues to run in the background, even when the activity is closed. I bind to this service since I want to re-use the same service when the activity is stopped and resumed.
MainActivity.java
//Service button click listener
startSvcButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(new Intent(MainActivity.this, ForegroundService.class));
startService(new Intent(MainActivity.this, ForegroundService.class));
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
moveTaskToBack(true);
}
});
In the service class the service is started as follows: ForegroundService.java
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, serviceNotification);
return Service.START_STICKY;
The problem I have is that when the MainActivity
is stopped, unBind
is called, which is good, but when I resume the MainActivity
and call bindService
again, it never happens.
The foreground service is running, I call bindService
again from the onResume
of the activity but mBound
and mService
stays null, even when I accommodate the async bindService
(I know the while loop is not good but it is for debugging)
The serviceConnection
is ok.
MainActivity.class:
if (fsRunning) {
if (!mBound) {
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
do {
SystemClock.sleep(500);
} while (!mBound);
}
How do I get the foreground service to rebind to MainActivity
after on onStop
of the activity and triggering a new bindService
?