微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android的服务被杀

如何解决Android的服务被杀

我试图让一个Android应用程序。它应该做的事时,电话被连接到特定WiFi网络,什么事都不做的时候休息。我使用的是ServicebroadcastReceiver。一切工作正常,但检查无线网络连接状态下的服务被杀害在几秒钟没有理由后,我躲在我的应用程序。是否有可能使它执着? 我知道android:persistent标志,但它似乎是无用的,我为我的应用程序是不是系统。

解决方法

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。