安卓服务被杀



我正在尝试制作一个android应用程序。当手机连接到特定的wifi网络时,它应该做一些事情,而在剩下的时间里什么都不做。我使用ServiceBroadcastReceiver。一切都很好,但在我隐藏应用程序后的几秒钟内,检查wifi状态的服务莫名其妙地被终止了。有可能使它持久吗?我知道android:persistent标志,但它对我来说似乎没用,因为我的应用程序不是系统。

从Android Oreo开始,应用程序关闭时不允许运行后台服务,因此您必须从前台启动它(谷歌建议使用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))
}
}
}

最新更新