首页 > 解决方案 > Android服务被杀死

问题描述

我正在尝试制作一个android应用程序。当手机连接到特定的 wifi 网络时,它应该做一些事情,其余时间什么都不做。我使用 aService和 a BroadcastReceiver。一切正常,但是在我隐藏我的应用程序后的几秒钟内,检查 wifi 状态的服务会无缘无故地被杀死。有没有可能让它持久化?我知道android:persistent标志,但它对我来说似乎没用,因为我的应用程序不是系统。

标签: androidkotlinservicewifimanager

解决方案


从 Android Oreo 开始,应用程序关闭时不允许运行后台服务,因此您必须在前台启动它(Google 建议对 SDK > Oreo 使用 JobScheduler)。这当然不是完美的解决方案,但应该可以帮助您入门。

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))
            }
        }
    }

推荐阅读