问题
I am building an application just like Spotify using ExoPlayer. I am starting a player notification when the song starts playing and it should be getting played even when the app is put into the background. Therefore, I need to release the player and save the last played song when the user deliberately clears the app off from the Ram but onDestory()
is not reliable as stated here. So, I thought doing resource cleaning in onActivityDestroyed()
in a custom Application but that failed too.
override fun onActivityDestroyed(activity: Activity?) {
val activityName = activity!!.localClassName
Log.d(TAG, "onActivityDestroyed: activity name ==> $activityName")
val musicPlayerDAO =
MusicPlayerDatabase.getDatabase(applicationContext).musicPlayerDao()
val repository = Repository(musicPlayerDAO)
val job = Job()
CoroutineScope(Dispatchers.IO + job).launch {
repository.insertLastPlayedSong(LastPlayedSongEntity("Dummy title", 3000))
}
Log.d(TAG, "onActivityDestroyed: Just after the co-routine")
}
Only the first log is getting executed here. What is the best possible way of freeing up resources in this case?
回答1:
You should free your resource in onStop()
, when activity goes into background it is stopped but not destroyed(unless the system kills the activity's hosting process).If you release resources in onDestroy()
, which is not called by default when Activity goes to background, the Activity will hold to these resources while in stopped state, thus causing higher amount of resources to be consumed by your app in background state.
来源:https://stackoverflow.com/questions/58597212/what-is-the-best-way-to-clear-up-resources-in-android