[英]Android background service never stops
我剛剛了解 Android 中的服務。我沒有使用任何 stopService() function,但我希望我的服務在我終止應用程序后立即停止工作(通過關閉它並將其從最近的屏幕中刪除)。那沒有發生並且我的日志消息繼續打印。
這是我正在使用的服務 class
class NormalServiceClass : Service() {
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
thread {
while (true) {
Log.d("NORMALSERVICECLASS", "Service working")
Log.d("NORMALSERVICECLASS", Thread.currentThread().name)
Thread.sleep(2000)
}
}
return super.onStartCommand(intent, flags, startId)
}
}
我正在使用 Activity 啟動服務
startService(Intent(this,NormalServiceClass::class.java))
為什么會這樣,因為它不是前台服務。
你停止服務了嗎?
stopService(Intent(this,NormalServiceClass::class.java));
首先,您通過像這樣進行無限循環來增加系統開銷:
while (true) {
因此,首先解決該錯誤,其次停止服務這樣的事情就足夠了。
stopSelfResult(startId)
return super.onStartCommand(intent, flags, startId)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.