That works for me pretty well, tested several hours of continuous operation with some emulators and Android 6.0 and 7.1 real devices, network connection never lost :
In the Main Activity onPause I acquire a Partial WakeLock and I start a Service with STARTFOREGROUND_ACTION intent, the Service calls startForeground and shows a Notification.
On Activity onResume the WakeLock is released, the Service stops with STOPFOREGROUND_ACTION intent and the Service itself calls stopForeground & stopSelf.
And also that avoids Activity to be destroyed on Back Key press :
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
Of course I provide a menu option to stop the background porcessing and finish the Activity
My code that periodically ask an internet server is placed in the Activity, it uses a timer.
Hope it will help