public class VolumeEaseHelper
extends java.lang.Object
使用步骤:
VolumeEaseHelper
对象;MusicPlayer.start()
与 MusicPlayer.pause()
方法分别代理给
start()
与 pause()
方法,并在
VolumeEaseHelper.Callback
中实现真正的 MusicPlayer.start()
与 MusicPlayer.pause()
逻辑;MusicPlayer.quiet()
与 MusicPlayer.dismissQuiet()
方法分别代理给
quiet()
与 dismissQuiet()
方法;MusicPlayer.stop()
与 MusicPlayer.release()
方法中调用
cancel()
方法,否则会有内存泄露的风险。例:
public class MyMusicPlayer implements MusicPlayer { ... private VolumeEaseHelper mVolumeEaseHelper; public MediaMusicPlayer() { ... mVolumeEaseHelper = new VolumeEaseHelper(this, new VolumeEaseHelper.Callback() { @Override public void start() { // 在该方法中实现真正的 start 逻辑 mMediaPlayer.start(); } @Override public void pause() { // 在该方法中实现真正的 pause 逻辑 mMediaPlayer.pause(); } }); } @Override public void start() { // 将 start 方法代理给 VolumeEaseHelper 对象的 start 方法 mVolumeEaseHelper.start(); } @Override public void pause() { // 将 pause 方法代理给 VolumeEaseHelper 对象的 pause 方法 mVolumeEaseHelper.pause(); } @Override public void stop() { // 在 stop 方法中调用 VolumeEaseHelper 对象的 cancel 方法 mVolumeEaseHelper.cancel(); ... } @Override public synchronized void release() { // 在 release 方法中调用 VolumeEaseHelper 对象的 cancel 方法 mVolumeEaseHelper.cancel(); ... } @Override public void quiet() { // 可选:将 quiet 方法代理给 VolumeEaseHelper 对象的 quiet 方法 mVolumeEaseHelper.quiet(); } @Override public void dismissQuiet() { // 可选:将 dismissQuiet 方法代理给 VolumeEaseHelper 对象的 dismissQuiet 方法 mVolumeEaseHelper.dismissQuiet(); } }
如果你觉得这很繁琐,可以继承 AbstractMusicPlayer
类,该类已对
VolumeEaseHelper
进行了封装,可以减少模板代码。
AbstractMusicPlayer
限定符和类型 | 类和说明 |
---|---|
static interface |
VolumeEaseHelper.Callback
回调接口,请在该接口中实现真正的 start 与 pause 逻辑。
|
构造器和说明 |
---|
VolumeEaseHelper(MusicPlayer musicPlayer,
VolumeEaseHelper.Callback callback)
创建一个
VolumeEaseHelper 对象。 |
public VolumeEaseHelper(@NonNull MusicPlayer musicPlayer, @NonNull VolumeEaseHelper.Callback callback)
VolumeEaseHelper
对象。musicPlayer
- MusicPlayer 对象,不能为 nullcallback
- 回调接口,不能为 null。请在该回调接口中实现正在的 start 与 pause 逻辑。