如何保持MediaPlayer的[机器人]单个实例机器人、实例、MediaPlayer

2023-09-07 10:36:01 作者:伴人一霎

我使用的Andr​​oid媒体播放器类,用于播放通知声音在我的Andr​​oid应用程序。

I am using android media player class for playing notification sound in my android Application.

MediaPlayer player = MediaPlayer.create(getApplicationContext(), R.raw.notify);
player.setLooping(false);
player.start();

我需要扮演不同的通知声音在不同的活动,所以每次我要玩,我需要创建的媒体播放器实例,然后我需要说的启动声音。

I need to play different notification sounds in different Activities, so every time i need to play the sound i need to create media player instance and then i need to say start.

不过。

有人可以请建议我实现它的更好的方法。 从我的角度来看,我将创建一个单独的类,我会添加所有在这个类的相关功能的MediaPlayer。

Can someone please suggest me the better way of implementing it. From my point of view i will create one singleton class and i will add all the MediaPlayer related function in this class.

感谢。

推荐答案

您应该考虑在 Singleton模式 。使类MyPlayer,有一个静态方法 getMediaPlayer()返回的MediaPlayer的同一个实例每次调用的时候。

You should consider the Singleton pattern. Make a class MyPlayer that has a static method getMediaPlayer() that returns the same instance of MediaPlayer each time called.