Improve service restarting

And fixes a memory leak
This commit is contained in:
sim 2022-01-17 20:56:40 +01:00
parent aee6c597f3
commit 31cf3fb21a
3 changed files with 15 additions and 3 deletions

View File

@ -32,6 +32,7 @@ import org.unifiedpush.distributor.nextpush.api.apiDeleteApp
import org.unifiedpush.distributor.nextpush.api.apiDeleteDevice
import org.unifiedpush.distributor.nextpush.distributor.sendUnregistered
import org.unifiedpush.distributor.nextpush.distributor.getDb
import org.unifiedpush.distributor.nextpush.services.isServiceStarted
import org.unifiedpush.distributor.nextpush.services.startListener
import java.lang.String.format
@ -144,6 +145,7 @@ class MainActivity : AppCompatActivity() {
private fun restart() {
Log.d(TAG, "Restarting the Listener")
isServiceStarted = false
val serviceIntent = Intent(this, StartService::class.java)
this.stopService(serviceIntent)
startListener(this)

View File

@ -67,6 +67,8 @@ class SSEListener (val context: Context) : EventSourceListener() {
}
override fun onClosed(eventSource: EventSource) {
if (!isServiceStarted)
return
Log.d(TAG, "onClosed: $eventSource")
nFails += 1
createWarningNotification(context)
@ -74,6 +76,8 @@ class SSEListener (val context: Context) : EventSourceListener() {
}
override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
if (!isServiceStarted)
return
Log.d(TAG, "onFailure")
nFails += 1
if (nFails > 1)
@ -93,6 +97,7 @@ class SSEListener (val context: Context) : EventSourceListener() {
override fun onTick(millisUntilFinished: Long) {}
override fun onFinish() {
if (nFails > 0)
Log.d(TAG, "Trying to restart")
startListener(context)
}

View File

@ -19,6 +19,7 @@ import android.net.Network
import android.net.ConnectivityManager
import android.net.ConnectivityManager.NetworkCallback
import android.net.NetworkCapabilities
import org.unifiedpush.distributor.nextpush.api.apiDestroy
import org.unifiedpush.distributor.nextpush.api.apiSync
import java.lang.Exception
@ -30,6 +31,7 @@ var nFails = 0
var wakeLock: PowerManager.WakeLock? = null
fun startListener(context: Context){
if (isServiceStarted && nFails == 0) return
Log.d(TAG, "Starting the Listener")
val serviceIntent = Intent(context, StartService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
@ -49,7 +51,7 @@ class StartService: Service(){
override fun onCreate(){
super.onCreate()
Log.i(TAG,"Starting")
Log.i(TAG,"StartService created")
val notification = createForegroundNotification(this)
startForeground(NOTIF_ID_FOREGROUND, notification)
}
@ -67,6 +69,7 @@ class StartService: Service(){
override fun onDestroy() {
Log.d(TAG, "Destroyed")
if (isServiceStarted) {
apiDestroy()
startListener(this)
} else {
stopService()
@ -76,6 +79,8 @@ class StartService: Service(){
private fun stopService() {
Log.d(TAG, "Stopping Service")
apiDestroy()
isServiceStarted = false
nFails = 0
wakeLock?.let {
while (it.isHeld) {
it.release()