What is the best way to clear up resources in Android?

二次信任 提交于 2020-01-25 06:48:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!