当用户切换到 Android Studio Kotlin 中的其他页面时,如何停止播放音乐?

Posted

技术标签:

【中文标题】当用户切换到 Android Studio Kotlin 中的其他页面时,如何停止播放音乐?【英文标题】:How to stop music from playing when user switch to other page in Android Studio Kotlin? 【发布时间】:2021-12-01 16:27:03 【问题描述】:

我创建了一个冥想应用程序,用户可以从片段内的回收器视图中选择他们想要的课程,然后它将显示新活动中的详细内容和步骤。在新活动中,我实现了音频播放功能,用户可以在其中从 firebase 流式传输音频文件。现在的问题是,每当我切换回片段中的回收器视图时,音频文件仍在后台播放。每当我切换到应用内的另一个页面或切换到另一个应用时,如何停止播放音频文件?

这是片段中回收器视图的代码

class ClassFragment : Fragment() 

private lateinit var recyclerView: RecyclerView
private lateinit var classArrayList: ArrayList<Classes>
private lateinit var tempArraylist: ArrayList<Classes>
private lateinit var classAdapter: ClassAdapter
private lateinit var db: FirebaseFirestore
var mediaPlayer: MediaPlayer? = null

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? 
    val view: View = inflater.inflate(R.layout.fragment_class, container, false)
    recyclerView = view.findViewById(R.id.ClassList)
    recyclerView.layoutManager = LinearLayoutManager(context)
    recyclerView.setHasFixedSize(true)

    classArrayList = arrayListOf()
    tempArraylist = arrayListOf()
    eventChangeListener()
    classAdapter = ClassAdapter(requireContext(), classArrayList)

    recyclerView.adapter = classAdapter

    return view



private fun eventChangeListener() 
    db = FirebaseFirestore.getInstance()
    db.collection("class").addSnapshotListener(object : EventListener<QuerySnapshot> 
        override fun onEvent(value: QuerySnapshot?, error: FirebaseFirestoreException?) 
            if (error != null) 
                Log.e("Firestore error", error.message.toString())
                return
            
            for (dc: DocumentChange in value?.documentChanges!!) 
                if (dc.type == DocumentChange.Type.ADDED) 

                    classArrayList.add(
                        dc.document.toObject(
                            (Classes::class.java)
                        )
                    )
                
            
            tempArraylist.clear()
            tempArraylist.addAll(classArrayList)
            classAdapter.notifyDataSetChanged()
        
    )

这是新活动页面的代码,当用户从回收站视图中选择时,它将显示内容

class DetailActivity : AppCompatActivity() 

private lateinit var imageViewClass: ImageView
private lateinit var textViewClassName: TextView
private lateinit var textViewClassDes: TextView
private lateinit var textViewClassContent: TextView
private var stop:Boolean = false
var mediaPlayer: MediaPlayer? = null
override fun onCreate(savedInstanceState: Bundle?) 
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_detail)
    val btnPlay: Button = findViewById(R.id.btnPlay)
    val btnStop: Button = findViewById(R.id.btnStop)


    imageViewClass = findViewById(R.id.imageViewClassImage)
    textViewClassName = findViewById(R.id.textViewClassName)
    textViewClassDes = findViewById(R.id.textViewClassDescription)
    textViewClassContent = findViewById(R.id.textViewClassContent)


    val classImage = intent.getStringExtra("class_image")
    val className = intent.getStringExtra("class_name")
    val classDes = intent.getStringExtra("class_des")
    val classContent = intent.getStringExtra("class_content")
    val classAudio = intent.getStringExtra("class_audio")

    Glide.with(this)
        .load(classImage)
        .centerCrop()
        .into(imageViewClass)
    textViewClassName.text = className
    textViewClassDes.text = classDes
    textViewClassDes.text = classDes!!.replace("\\n", "\n")
    textViewClassContent.text = classContent
    textViewClassContent.text = classContent!!.replace("\\n", "\n")

    btnPlay.isEnabled = true
    btnStop.isEnabled = false

    btnPlay.setOnClickListener(object : View.OnClickListener 
        override fun onClick(v: View?) 
            if (mediaPlayer == null) 
                mediaPlayer = MediaPlayer.create(this@DetailActivity, Uri.parse(classAudio))
                mediaPlayer!!.isLooping = true
                mediaPlayer!!.start()
                btnStop.isEnabled = true
                btnPlay.isEnabled = false
                Toast.makeText(applicationContext,"Audio Starts",Toast.LENGTH_SHORT).show()
             else mediaPlayer!!.start()

        

    )

    mediaPlayer?.setOnCompletionListener 
        btnPlay.isEnabled = true
        btnStop.isEnabled = false
        Toast.makeText(this,"end",Toast.LENGTH_SHORT).show()
    

    btnStop.setOnClickListener(object : View.OnClickListener 
        override fun onClick(v: View?) 
            if(mediaPlayer!!.isPlaying)
                stop = false
                mediaPlayer!!.stop()
                mediaPlayer!!.reset()
                mediaPlayer!!.release()
                mediaPlayer = null
                btnPlay.isEnabled = true
                btnStop.isEnabled = false
                Toast.makeText(applicationContext,"Audio Stops",Toast.LENGTH_SHORT).show()
            
        
    )


【问题讨论】:

【参考方案1】:

这是onDestroy 的经典案例Activity 被调用。我会保持简短,但是Activity 经历了一个生命周期,当您似乎从 SecondActivity 回到第一个 Activity 时,会调用您的第二个 Activity 的 onDestroy 来执行销毁功能

所以解决方案,覆盖 DetailActivity 类中的 onDestroy 方法并执行类似的操作

override fun onDestroy()
 if(mediaPlayer != null)
   mediaPlayer!!.stop()
   mediaPlayer!!.reset()
   mediaPlayer!!.release()
   mediaPlayer = null
 

你可以详细阅读Activity Lifecyle

【讨论】:

以上是关于当用户切换到 Android Studio Kotlin 中的其他页面时,如何停止播放音乐?的主要内容,如果未能解决你的问题,请参考以下文章

android studio怎么切换到原代码编写界面

无法在 Android Studio 中切换到调试构建变体

Android studio多个项目之间怎么实现快速切换?

Android Studio:无法切换到新活动

Android Studio 中的 Facebook SDK 4 ExceptionInitializeError Login v2.3

当我离开我的应用程序时如何停止 MediaPlayer,而不是当我移动到另一个 Activity 时(Android Studio)