I need to make a service to catch server messages via websocket and show them in the notification.
First time when I closed the app the service stopped. I made a broadcast receiver in onDestroy to restart service after app is closed and swiped from active apps.
But after all system or some other things keep killing the service exactly every 10 seconds.
I see Not finishing the service, sending broadcast in logcat, so it wasn't me stopping the service using the command.
"Start command" message appears every 10 seconds in logcat, it means the service keeps restarting every 10 seconds.
NotificationPuller.kt:
import android.app.Notification
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.util.Log
import com.packagename.project.ENDPOINT_SERVER_WS
import com.packagename.project.PREFS
import com.packagename.project.PREFS_TOKEN
import com.packagename.project.UnsafeHttpClient
import com.packagename.project.receivers.ServiceRestart
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.WebSocket
import java.util.*
class NotificationPuller : Service() {
private var finishing: Boolean = false
override fun onBind(intent: Intent): IBinder? {
Log.d(TAG, "Service binding")
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d(TAG, "Start command")
return START_STICKY
}
private fun onCriticalFailure() {
Log.d(TAG, "Critical failure, stopping the service")
stopService()
}
private fun onFailure() {
Log.d(TAG, "Connection failure")
}
override fun onDestroy() {
super.onDestroy()
if(!finishing) { // not killing the service completely, restarting it
Log.d(TAG, "Not finishing the service, sending broadcast")
val broadcastIntent = Intent()
broadcastIntent.setClass(this, ServiceRestart::class.java)
broadcastIntent.action = RESTART_ACTION
sendBroadcast(broadcastIntent)
} else
Log.d(TAG, "Service destroyed")
}
private fun stopService() {
finishing = true
stopSelf()
}
companion object {
private const val TAG = "SERVICE"
const val RESTART_ACTION = "com.nikitiyproject.RESTART_ACTION"
}
}
ServiceRestart.kt
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.core.content.ContextCompat
import androidx.core.content.IntentCompat
import com.packagename.project.background.NotificationPuller
class ServiceRestart : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.d(TAG, "BroadcastReceiver restarts service")
val serviceIntent = Intent(context!!, NotificationPuller::class.java)
ContextCompat.startForegroundService(context, serviceIntent)
}
companion object {
private const val TAG = "BCR"
}
}