重新打开应用程序后,将创建服务的多个实例

时间:2018-11-18 23:44:20

标签: android kotlin android-service android-notifications

我正在尝试创建一个应用程序来更新持久性通知,即使该应用程序已关闭。现在,我正在使用MainActivity的onCreate()中启动的服务:

serviceIntent = Intent(this, PersistentService::class.java)
val stopped = stopService(serviceIntent)
println("[123] stopped: $stopped")
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    startForegroundService(serviceIntent)
} else {
    startService(serviceIntent)
}

这非常适合启动它。但是,当我重新打开并关闭该应用程序时,即使已停止:打印出true,该先前的服务仍在运行,并且未调用该先前的服务的stopService()。

精简的PersistentService类版本:

var timesStarted = 0
var lastService: PersistentService? = null

class PersistentService: Service(){
    private var timer: Timer? = null
    private var task: AsyncTask<*, *, *>? = null

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        timesStarted++
        println("[123]starting persistent service. timesStarted: $timesStarted lastService===this: ${lastService===this} lastService==this: ${lastService==this} lastService: $lastService")
        println("[123] hashCode: ${hashCode()}")
        lastService = this
        if(timer == null){
            timer = Timer()
        }
        setToLoadingNotification()
        timer?.scheduleAtFixedRate(object : TimerTask(){
            override fun run(){
                println("[123]Updating hashCode: ${this@PersistentService.hashCode()}")
                if(task?.status == AsyncTask.Status.RUNNING){
                    // send notification saying last request timed out
                }
                task?.cancel(true)

                task = DataUpdaterTask(DatabaseDataRequester { GlobalData.connectionProperties }) { dataRequest ->
                    // send notification based on dataRequest value
                }.execute()
            }
        }, 1000L, UPDATE_PERIOD)
        return START_STICKY
    }

    private fun notify(notification: Notification){
        getManager().notify(NOTIFICATION_ID, notification)
        startForeground(NOTIFICATION_ID, notification)
    }
    private fun getBuilder(): Notification.Builder {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            return Notification.Builder(this, NotificationChannels.PERSISTENT_STATUS.id)
        }
        return Notification.Builder(this)
    }
    private fun getManager() = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    override fun stopService(name: Intent?): Boolean {
        println("[123]Stopping persistent service")
        timer?.cancel() // stop the timer from calling the code any more times
        task?.cancel(true) // stop the code from running if it's running
//        getManager().cancel(NOTIFICATION_ID)
        return super.stopService(name)
    }
}

这是输出

[123] stopped: false
[123]starting persistent service. timesStarted: 1 lastService===this: false lastService==this: false lastService: null
[123] hashCode: 4008007
[123]Updating hashCode: 4008007
[123]Got successful data request
[123]Updating hashCode: 4008007
[123]Got successful data request
// *close and reopen the app*
[123] stopped: true
[123]starting persistent service. timesStarted: 2 lastService===this: false lastService==this: false lastService: me.retrodaredevil.solarthing.android.PersistentService@3d2847
[123] hashCode: 7823272
[123]Updating hashCode: 7823272
[123]Got successful data request
[123]Updating hashCode: 4008007
[123]Got successful data request
[123]Updating hashCode: 7823272
[123]Got successful data request

从输出中可以看到,两个服务同时运行。哈希码表明它们不是同一对象,因此如果我将代码放在onCreate()而不是onStartCommand()上也没关系(无论如何我都已经测试过了)

如果有人可以指出正确的方向,这将对您有所帮助。我是android开发的新手,我找不到正确的方法来执行此操作。我什至不确定我现在正在做什么是更新通知的最佳方法。

1 个答案:

答案 0 :(得分:3)

  

和先前服务的stopService()没有被调用。

stopService()不是Service的生命周期方法。也许您在考虑onDestroy()

  

先前的服务仍在运行

否,先前的服务实例已停止。您刚刚泄漏了Timer,因为您没有取消Timer中的onDestroy()

因此,覆盖onDestroy(),将您的cancel()呼叫放在那里,摆脱stopService()的其余部分,您的状态应该会更好。