android - Android服务被杀死
问题描述
我正在尝试制作一个android应用程序。当手机连接到特定的 wifi 网络时,它应该做一些事情,其余时间什么都不做。我使用 aService
和 a BroadcastReceiver
。一切正常,但是在我隐藏我的应用程序后的几秒钟内,检查 wifi 状态的服务会无缘无故地被杀死。有没有可能让它持久化?我知道android:persistent
标志,但它对我来说似乎没用,因为我的应用程序不是系统。
解决方案
从 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))
}
}
}
推荐阅读
- xml - 使用 XSLT 将 XML 转换为 XML 删除前导空格和零
- javascript - 实例上的正则表达式总匹配
- c++ - 行数和列数不匹配时输出不正确
- javascript - Multiple dropdown redirect to URL ( HTML )
- windows-10 - 无法通过 Anaconda Navigator 安装 Spyder
- javascript - 调用 jQuery.validate 的 showErrors 函数时出现 TypeError
- laravel - Laravel,获取关系数据
- python - 为什么第 13 行 a = input() 会影响第 15 行 b = input(int() 上的变量?python3
- java - 将一个存储库用于多个 Dao 是最佳实践 MVVM 吗?
- c# - 实现接口与添加新方法之间有区别吗?