0

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?

Neeraj Sewani
  • 3,952
  • 6
  • 38
  • 55

1 Answers1

0

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.

Mohammad Sianaki
  • 1,425
  • 12
  • 20
  • Freeing up resources in `onStop` would mean stopping the player and hence the music but the music has to be played when the app goes into the background. – Neeraj Sewani Oct 28 '19 at 20:23
  • @neer17 to do something while app is in background you should use `Service` component not `Activity` – Mohammad Sianaki Oct 28 '19 at 21:01
  • PlayerNotificationManager is taking care of the foreground service. Anyway, my concern is releasing the player and insert the last played song into the db when the app is destroyed. – Neeraj Sewani Oct 29 '19 at 06:16