Skip to content

Commit

Permalink
Fix naming issues, fix cannot pause music after recreate music player…
Browse files Browse the repository at this point in the history
… service
  • Loading branch information
LinZong committed Apr 29, 2021
1 parent bfff510 commit dbc5f90
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 68 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -59,41 +59,40 @@ class MusicControlActivity : MusicPlayerActivity() {
field = value
}

private var PendingPrepareURL = ""
private var PlayerService: MusicPlayerService? = null
private var pendingPrepareURL = ""
private var playerService: MusicPlayerService? = null
private var player: MusicPlayer? = null
private var CurrentMusicTotalDuration = 0
private var currentMusicTotalDuration = 0
private val timeElapsedUpdater = Handler(this::handleQueryTimeStamp)

private val PlayerServiceConnection = object : ServiceConnection {
private val playerServiceConnection = object : ServiceConnection {
override fun onServiceDisconnected(componentName: ComponentName?) {
Log.d("MusicControlActivity", "音乐播放器服务取消绑定.")
PlayerService = null
playerService = null
}

override fun onServiceConnected(componentName: ComponentName?, service: IBinder?) {
PlayerService = (service as MusicPlayerService.MusicPlayerBinder).getService()
Log.d("MusicControlActivity", "音乐播放器服务Bind完成 ${PlayerService.hashCode()}")
PlayerService?.let { ps -> player = ps.player }
SubscribeMusicPlayerStatus()
playerService = (service as MusicPlayerService.MusicPlayerBinder).getService()
Log.d("MusicControlActivity", "音乐播放器服务Bind完成 ${playerService.hashCode()}")
playerService?.let { ps -> player = ps.player }
subscribeMusicPlayerStatus()
}
}



override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
InitView()
LoadUserPreferenceSetup()
PrepareActivityStatus()
initView()
loadUserPreferenceSetup()
prepareActivityStatus()
}

override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
LoadUserPreferenceSetup()
loadUserPreferenceSetup()
}

private fun InitView() {
private fun initView() {
listOf(
MusicPlayer_Control_Play,
MusicPlayer_Control_MoreInfo,
Expand All @@ -110,8 +109,8 @@ class MusicControlActivity : MusicPlayerActivity() {
else -> {}
}
} else {
PendingPrepareURL = CurrentMusicPlayInfo?.URL ?: ""
StartMusicPlayService(true)
pendingPrepareURL = CurrentMusicPlayInfo?.URL ?: ""
startMusicPlayService(true)
}
}, {
val intent = Intent(this, MusicDetailActivity::class.java)
Expand All @@ -124,30 +123,30 @@ class MusicControlActivity : MusicPlayerActivity() {
}, {
PrevMusic()
})
InitSeekbarController()
initSeekbarController()
}

private fun LoadUserPreferenceSetup() {
private fun loadUserPreferenceSetup() {
isEnableLooping = Persistence.GetMusicPlayerLoopStatus()
}

private fun PrepareActivityStatus() {
private fun prepareActivityStatus() {
val status = intent.getSerializableExtra(PERSIST_STATUS_INTENT_KEY)
StartMusicPlayService(onlyBindService = status != null)
startMusicPlayService(onlyBindService = status != null)
if (status != null) {
// 从通知栏消息过来.
fromNotificationIntent = true
newMusicLoaded = false
val activityStatus = status as MusicPlayerActivityStatus
RecoverActivityStatusFromPersistObject(activityStatus)
recoverActivityStatusFromPersistRecord(activityStatus)
} else {
fromNotificationIntent = false
// 从点击RecommendItem过来
val MusicContentUrl = intent.getStringExtra(MUSIC_CONTENT_URL) ?: ""
val musicContentUrl = intent.getStringExtra(MUSIC_CONTENT_URL) ?: ""
if (LAST_MUSIC_PLAYER_ACTIVITY_STATUS != null) {
// 恢复
RecoverActivityStatusFromPersistObject(LAST_MUSIC_PLAYER_ACTIVITY_STATUS!!)
} else if (MusicContentUrl.isNotEmpty()) {
recoverActivityStatusFromPersistRecord(LAST_MUSIC_PLAYER_ACTIVITY_STATUS!!)
} else if (musicContentUrl.isNotEmpty()) {
newMusicLoaded = true
}
}
Expand All @@ -170,12 +169,11 @@ class MusicControlActivity : MusicPlayerActivity() {
timeElapsedUpdater.removeMessages(100)
}

private fun InitSeekbarController() {
private fun initSeekbarController() {
MusicPlayer_Seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekbar: SeekBar?, progress: Int, fromUser: Boolean) {
if (fromUser) {
MusicPlayer_CurrentTime.text =
(Duration2Time(Progress2Duration(progress, CurrentMusicTotalDuration)))
MusicPlayer_CurrentTime.text = Duration2Time(Progress2Duration(progress, currentMusicTotalDuration))
}
}

Expand All @@ -192,48 +190,47 @@ class MusicControlActivity : MusicPlayerActivity() {
})
}

private fun RecoverActivityStatusFromPersistObject(activityStatus: MusicPlayerActivityStatus) {
private fun recoverActivityStatusFromPersistRecord(activityStatus: MusicPlayerActivityStatus) {
Log.d("MusicControlActivity", "MusicControlActivity 开始恢复上一次的Activity状态")
CurrentMusicTotalDuration = activityStatus.musicTotalDuration
currentMusicTotalDuration = activityStatus.musicTotalDuration
MusicPlayer_Seekbar.progress = activityStatus.seekbarProgress
MusicPlayer_CurrentTime.text = Duration2Time(
Progress2Duration(activityStatus.seekbarProgress, activityStatus.musicTotalDuration)
)
MusicPlayer_TotalTime.text = Duration2Time(CurrentMusicTotalDuration)
MusicPlayer_TotalTime.text = Duration2Time(currentMusicTotalDuration)
MusicPlayer_Seekbar.secondaryProgress = activityStatus.bufferBarProgress
}

private fun CanPersistMusicPlayerActivityStatus() =
private fun allowPersistMusicPlayerActivityStatus() =
relatedMusicListData != null &&
lyricListData != null &&
CurrentMusicContentInfo != null &&
CurrentMusicPlayInfo != null && PLAY_LISTS != null

fun PersistMusicPlayerActivityStatus(playerAction: PlayerAction, AlsoUpdateActivityIntent: Boolean) {
if (CanPersistMusicPlayerActivityStatus()) {
val ActivityStatusModel = MusicPlayerActivityStatus(
fun persistMusicPlayerActivityStatus(playerAction: PlayerAction, AlsoUpdateActivityIntent: Boolean) {
if (allowPersistMusicPlayerActivityStatus()) {
val statusRecord = MusicPlayerActivityStatus(
relatedMusicListData!!,
lyricListData!!,
CurrentMusicPlayInfo!!,
CurrentMusicContentInfo!!,
CurrentMusicTotalDuration,
currentMusicTotalDuration,
MusicPlayer_Seekbar.progress,
MusicPlayer_Seekbar.secondaryProgress,
isEnableLooping,
CurrentPlayItemIndex,
PLAY_LISTS!!
)
if (AlsoUpdateActivityIntent)
PlayerService?.UpdateWakeupMusicPlayerActivityIntent(ActivityStatusModel)
LAST_MUSIC_PLAYER_ACTIVITY_STATUS = ActivityStatusModel
if (AlsoUpdateActivityIntent) {
playerService?.UpdateWakeupMusicPlayerActivityIntent(statusRecord)
}
LAST_MUSIC_PLAYER_ACTIVITY_STATUS = statusRecord
LAST_PLAYER_STATUS = playerAction
}
}




private fun SubscribeMusicPlayerStatus() {
private fun subscribeMusicPlayerStatus() {
player?.looping(isEnableLooping)
player?.registerStateChangedListener(object : DefaultMusicPlayerStateChangedCallback() {

Expand All @@ -248,35 +245,38 @@ class MusicControlActivity : MusicPlayerActivity() {

override fun onPlaying(player: MusicPlayer) {
MusicPlayer_Seekbar.isEnabled = true
CurrentMusicTotalDuration = player.duration().toInt()
currentMusicTotalDuration = player.duration().toInt()
player.looping(isEnableLooping)
MusicPlayer_TotalTime.text = Duration2Time(CurrentMusicTotalDuration)
PersistMusicPlayerActivityStatus(PlayerAction.PLAYING, true)
MusicPlayer_TotalTime.text = Duration2Time(currentMusicTotalDuration)
persistMusicPlayerActivityStatus(PlayerAction.PLAYING, true)
beginQueryTimeStamp()
MusicPlayer_Control_Play.setImageResource(R.drawable.ic_pause_red_600_24dp)
}

override fun onPausing(player: MusicPlayer) {
PersistMusicPlayerActivityStatus(PlayerAction.PAUSED, true)
stopQueryTimeStamp()
MusicPlayer_Control_Play.setImageResource(R.drawable.ic_play_arrow_red_600_24dp)
persistMusicPlayerActivityStatus(PlayerAction.PAUSED, true)
}

override fun onLoadFailed(player: MusicPlayer) {
stopQueryTimeStamp()
ResetTimeIndicator()
resetTimeIndicator()
MusicPlayer_Control_Play.setImageResource(R.drawable.ic_play_arrow_red_600_24dp)
persistMusicPlayerActivityStatus(PlayerAction.STOPPED, false)
}

override fun onStopping(player: MusicPlayer) {
stopQueryTimeStamp()
repeat(10) { ResetTimeIndicator() }
repeat(10) { resetTimeIndicator() }
MusicPlayer_Control_Play.setImageResource(R.drawable.ic_play_arrow_red_600_24dp)
persistMusicPlayerActivityStatus(PlayerAction.STOPPED, true)
}

override fun onPlayFinished(player: MusicPlayer) {
MusicPlayer_Seekbar.isEnabled = false
MusicPlayer_Control_Play.setImageResource(R.drawable.ic_play_arrow_red_600_24dp)
persistMusicPlayerActivityStatus(PlayerAction.STOPPED, true)
}

override fun onBuffering(player: MusicPlayer) {
Expand All @@ -285,23 +285,23 @@ class MusicControlActivity : MusicPlayerActivity() {

override fun onUnregistered(player: MusicPlayer) {
stopQueryTimeStamp()
ResetTimeIndicator()
resetTimeIndicator()
MusicPlayer_Control_Play.setImageResource(R.drawable.ic_play_arrow_red_600_24dp)
}

private fun recoverState(player: MusicPlayer) {
when (player.state()) {
PlayerAction.PLAYING -> {
PendingPrepareURL = ""
pendingPrepareURL = ""
beginQueryTimeStamp()
MusicPlayer_Control_Play.setImageResource(R.drawable.ic_pause_red_600_24dp)
}
PlayerAction.PAUSED -> {
MusicPlayer_Control_Play.setImageResource(R.drawable.ic_play_arrow_red_600_24dp)
}
PlayerAction.STOPPED -> {
if (PendingPrepareURL.isNotEmpty()) {
player.play(Uri.parse(PendingPrepareURL))
if (pendingPrepareURL.isNotEmpty()) {
player.play(Uri.parse(pendingPrepareURL))
}
MusicPlayer_Control_Play.setImageResource(R.drawable.ic_play_arrow_red_600_24dp)
}
Expand All @@ -311,28 +311,28 @@ class MusicControlActivity : MusicPlayerActivity() {
})
}

private fun ResetTimeIndicator() {
CurrentMusicTotalDuration = 0
private fun resetTimeIndicator() {
currentMusicTotalDuration = 0
MusicPlayer_Seekbar.progress = 0
MusicPlayer_Seekbar.secondaryProgress = 0
MusicPlayer_CurrentTime.text = Duration2Time(0)
MusicPlayer_TotalTime.text = Duration2Time(0)
}

private fun StartMusicPlayService(onlyBindService: Boolean = false) {
private fun startMusicPlayService(onlyBindService: Boolean = false) {
val intent = Intent(this, MusicPlayerService::class.java)
if (!onlyBindService) {
startService(intent)
}
bindService(intent, PlayerServiceConnection, Context.BIND_AUTO_CREATE)
SubscribeMusicPlayerStatus()
bindService(intent, playerServiceConnection, Context.BIND_AUTO_CREATE)
subscribeMusicPlayerStatus()
}

override fun onDestroy() {
if (player?.state() == PlayerAction.PLAYING || player?.state() == PlayerAction.PAUSED) {
PersistMusicPlayerActivityStatus(player!!.state(), true)
persistMusicPlayerActivityStatus(player!!.state(), true)
}
unbindService(PlayerServiceConnection)
unbindService(playerServiceConnection)
super.onDestroy()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package com.nemesiss.dev.piaprobox.Activity.Music

import android.app.AlertDialog
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
Expand Down Expand Up @@ -457,7 +456,7 @@ open class MusicPlayerActivity : PiaproboxBaseActivity() {
intent.action = "UPDATE_INFO"
intent.putExtra("UpdateMusicContentInfo", contentInfo)
intent.putExtra("WillPlayMusicURL", playInfo.URL)
(this as? MusicControlActivity)?.PersistMusicPlayerActivityStatus(PlayerAction.STOPPED, true)
(this as? MusicControlActivity)?.persistMusicPlayerActivityStatus(PlayerAction.STOPPED, true)
startService(intent)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ class MusicPlayerService : Service() {
)
)
if (!IS_FOREGROUND) {
ActAsForegroundService(pendingNewNotification)
bringToForegroundService(pendingNewNotification)
} else {
musicPlayerNotificationManager.notificationManager.notify(NotificationID, pendingNewNotification)
}
Expand All @@ -95,10 +95,10 @@ class MusicPlayerService : Service() {
val intent = Intent(PiaproboxApplication.Self.applicationContext, MusicControlActivity::class.java)
intent.putExtra(PERSIST_STATUS_INTENT_KEY, musicPlayerActivityStatus)
musicPlayerNotificationManager.activityIntent = intent
PlayingMusicContentInfo?.let { playingMusicContentInfo ->
PlayingMusicContentInfo?.let { contentInfo ->
UpdateNotification(
player.state(),
playingMusicContentInfo
contentInfo
)
}
}
Expand All @@ -107,12 +107,12 @@ class MusicPlayerService : Service() {
fun getService(): MusicPlayerService = this@MusicPlayerService
}

private fun ActAsForegroundService(notification: Notification) {
private fun bringToForegroundService(notification: Notification) {
IS_FOREGROUND = true
startForeground(NotificationID, notification)
}

override fun onBind(p0: Intent?): IBinder? {
override fun onBind(p0: Intent?): IBinder {
IS_BINDED = true
return MusicPlayerBinder()
}
Expand Down Expand Up @@ -159,12 +159,11 @@ class MusicPlayerService : Service() {
}

private fun stopPlaying() {
setServiceAvailable(false)
// setServiceAvailable(false)
player.stop()
stopForeground(true)
IS_FOREGROUND = false
musicPlayerNotificationManager.ClearNotification()
MusicPlayerActivity.CleanStaticResources()
Log.d("MusicPlayerService", "MusicPlayerService stopPlaying")
}

Expand Down

0 comments on commit dbc5f90

Please sign in to comment.