如何重新绑定已经运行的绑定音乐播放器服务

时间:2017-11-19 14:59:59

标签: android service kotlin android-mediaplayer

所以我只创建了一个音乐播放器应用程序和一个负责媒体播放器类的服务

当我在主活动中打开片段并从中播放音乐时,会调用该服务,发出通知并在后台运行...我用来调用该服务的代码是

val auroraServiceConnection = object : ServiceConnection {
    override fun onServiceConnected(className: ComponentName,
                                    service: IBinder) {
        // We've bound to LocalService, cast the IBinder and get LocalService instance
        val binder = service as AuroraService.LocalBinder
        mAuroraService = binder.service
        mBound = true
    }
    override fun onServiceDisconnected(arg0: ComponentName) {
        mBound = false
    }
}

fun play(id: Int){ // Called when play and changing music
    Log.v("aurora_l bound", mBound.toString())
    if(!mBound){
        val intent = Intent(activity, AuroraService::class.java)
        intent.action = AuroraService.ServiceAction.PLAY.value
        intent.putExtra("music_id", id)

        activity.startService(intent)
        activity.bindService(intent, auroraServiceConnection, Context.BIND_AUTO_CREATE)
        mBound = true
    } else {
        mAuroraService.changeMusic(Const.musicUtils.musicById(id))
    }

    update(AuroraService.PlaybackStatus.PLAYING, Const.musicUtils.musicById(id))

    mListener!!.onMusicStateChanged(AuroraService.PlaybackStatus.PLAYING)
}

问题是,当我关闭活动(服务仍在运行并播放音乐)并重新打开它,然后播放音乐,而不是使用旧服务,它创建了一个新服务并播放新歌..那么,有两种服务同时播放两种不同的音乐

但我希望只有一项服务,将重复使用

一些额外的数据

我的服务活页夹

class LocalBinder : Binder() {
        internal// Return this instance of LocalService so clients can call public methods
        val service: AuroraService
            get() = this@AuroraService
    }

来自我服务的onBind方法

override fun onBind(intent: Intent?): IBinder {
        initMediaSession() // Init media sessions class for notification
        iInitMediaPlayer() // Init mediaplayer callback
        if (intent != null) {
            iReceiveAction(intent)
        }
        return mBinder
    }

fun iReceiveAction(intent: Intent){
        val mAction = ServiceAction.values().lastOrNull { intent.action == it.value }
                ?: ServiceAction.NONE

        when (mAction){
            ServiceAction.PLAY -> {
                val musicId = intent.getIntExtra("music_id", -1)
                music = Const.musicUtils.musicById(musicId)
                musicInPlaylist = musicId
                playlist = ArrayList()

                plauMusic()
            }
            else -> {
                Log.v("aurora_", "?!")
            }
        }
    }

0 个答案:

没有答案