J
J
jenya_zhilin2020-04-28 12:53:24
Android
jenya_zhilin, 2020-04-28 12:53:24

How to stop MediaPlayer when app is closed?

Hello. How to stop the MediaPlayer when closing the application so that the user closes the application (minimizes) and the MediaPlayer stops.

package com.questend.quiz

import android.media.MediaPlayer
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    private lateinit var  mp: MediaPlayer
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mp = MediaPlayer.create(this, R.raw.sound)
        mp.start()
    }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jenya_zhilin, 2020-04-28
@jenya_zhilin

Thanks, but I found a solution. As it turned out, you need to use not destroy, but stop.

private lateinit var  mp: MediaPlayer
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mp = MediaPlayer.create(this, R.raw.sound)
        mp.start()
    }

    override fun onStop() {
        super.onStop()
        mp.release()
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question