0

I am trying to make an android app. It should do something when the phone gets connected to a particular wifi network, and do nothing the rest of the time. I use a Service and a BroadcastReceiver. Everything works fine, but the service for checking wifi state is killed for no reason in some seconds after I hide my application. Is it possible to make it persistent? I know about android:persistent flag, but it seems to be useless for me as my app isn't system.

RedMurloc
  • 115
  • 1
  • 11

1 Answers1

1

As of Android Oreo no background services are allowed to run when the app is closed so you must foreground start it (Google recommends using JobScheduler for SDK > Oreo).This is not the perfect solution of course but should get you started.

class NotificationService: Service() {
    
        private var notificationUtils = NotificationUtils(this)
        private var notificationManager: NotificationManager? = null
    
        override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
            super.onStartCommand(intent, flags, startId)
            return START_STICKY
        }
    
        override fun onCreate() {
            super.onCreate()

          //here checking if sdk > Oreo then start foreground or it will start by default on background

            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForeground(System.currentTimeMillis().toInt(), notificationUtils.foregroundNotification())
            }
        }
        override fun onDestroy() {
            super.onDestroy()

        // when the OS kills the service send a broadcast to restart it     
        
                val broadcastIntent = Intent(this, NotificationServiceRestarterBroadcastReceiver::class.java)
                sendBroadcast(broadcastIntent)          
        }
    
        override fun onBind(intent: Intent?): IBinder? {
            return null
        }        
    }




 class NotificationServiceRestarterBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent?) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(Intent(context, NotificationService::class.java))
            }else {
                 
                // if sdk < Oreo restart the background service normally 

                context.startService(Intent(context, NotificationService::class.java))
            }
        }
    }