2017-09-18 38 views
2

其onStart()中的Activity綁定到MusicPlayService,並且在其onStop()中取消綁定MusicPlayService。在它的onDestroy()調用的stopService,但MusicPlayService的的onDestroy()是沒有得到所謂的可言。未綁定並停止服務的onDestroy未調用

****** UPDATE:它是()的isFinishing在的onDestroy是假的。如果按下返回按鈕,activity :: onDestroy()就有isFinishing == true,並且如果按home按鈕調用onDestroy()(我有'不保持活動活着'設置選中),但isFinishing ==假。

我想這是正確的行爲,只有活動的結束()將開始設置isFinishing ==真。即使home按鈕會觸發onDestroy(),os仍然可能認爲這不是真正的「完成」。

想知道新牌坊生命週期LifecycleRegistryOwner可能提供了一些掛鉤的活動是真正被摧毀。

下面是活動的片段:

override fun onStart() { 
    super.onStart() 
    if (!isBound) { 
     val bindIntent = Intent(this, MusicPlayService::class.java) 
     isBound = bindService(bindIntent, myConnection, 
       Context.BIND_AUTO_CREATE) 
    } 
} 

override fun onStop() { 
    super.onStop() 
    unbindService(myConnection) 
    isBound = false 
} 


override fun onDestroy() { 
    super.onDestroy() 
    if (isFinishing) { 
     val intentStopService = Intent(this, MusicPlayService::class.java) 
     stopService(intentStopService) 
    } 
} 
+1

發現它是isFinishing導致該問題的檢查,但爲什麼當的onDestroy的isFinishing還是假的? – lannyf

回答

3

要回答你的問題,最終(轉述):

爲什麼會isFinishing永遠是虛假的onDestroy?

這裏的相關片段從the source code

* The final call you receive before your 
* activity is destroyed. This can happen either because the 
* activity is finishing (someone called {@link Activity#finish} on 
* it, or because the system is temporarily destroying this 
* instance of the activity to save space. You can distinguish 
* between these two scenarios with the {@link 
* Activity#isFinishing} method. 

所以isFinishing標誌是兩個不同的原因,區分了Activity破壞的幫手。

0

條件

if (isFinishing) { 
    val intentStopService = Intent(this, 
MusicPlayService::class.java) 
    stopService(intentStopService) 
} 

你是在的onDestroy)檢查(總是返回的onDestroy假。 isFinishing通常用於onPause()並在那裏返回true。由於onDestroy在活動已完成並且isFinished返回false之後被調用。因此,您的實施的服務銷燬代碼不會被執行。