如何解决在前台服务中播放Android VideoView的音频
我有一个Android应用程序,可以播放VideoView中的视频。当用户按下电话的主页按钮,并且应用程序转到后台时,我想继续播放视频的音轨。我正在使用前台服务。
class AudioService : Service() {
private val myBinder = MyBinder()
var mediaPlayer: MediaPlayer? = null
override fun onBind(intent: Intent?): IBinder? {
Log.d("AudioService","audio service bound")
return myBinder
}
override fun onUnbind(intent: Intent?): Boolean {
mediaPlayer = null
stopForeground(true)
return super.onUnbind(intent)
}
fun playAudio(mp: MediaPlayer) {
val notificationIntent = PendingIntent.getActivity(
this,Intent(this,MainActivity::class.java),PendingIntent.FLAG_UPDATE_CURRENT
)
val notificationBuilder =
createNotificationService("is playing audio",notificationIntent)
startForeground(
10700,notificationBuilder.build()
)
// not sure how can I assign VideoView's media player to service media player
mediaPlayer = mp
}
inner class MyBinder : Binder() {
fun getService(): AudioService {
return this@AudioService
}
}
}
这是我的MainActivity代码:
class MainActivity : AppCompatActivity() {
private lateinit var mediaPlayer: MediaPlayer
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
video_view.setOnPreparedListener { mp ->
mediaPlayer = mp
}
}
override fun onPause() {
super.onPause()
mediaPlayer?.let {
val intent = Intent(this,AudioService::class.java)
bindService(intent,audioServiceConnection,Context.BIND_AUTO_CREATE)
}
}
private val audioServiceConnection = object : ServiceConnection {
var isBound = false
override fun onServiceConnected(className: ComponentName,service: IBinder) {
val binder = service as AudioService.MyBinder
audioService = binder.getService()
if (video_view.visibility == View.VISIBLE) {
audioService?.playAudio(mediaPlayer)
}
isBound = true
}
override fun onServiceDisconnected(name: ComponentName) {
isBound = false
}
}
}
我可以将VideoView的媒体播放器分配给前台服务媒体播放器,这样在活动暂停(按下电话的主页按钮)时它不会停止播放吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。