我有一个播放音乐的应用程序。当应用程序开始加载时,音乐开始播放。歌曲的选择是随机的。在片段中显示歌曲的名称。正在播放音乐,但无法显示歌曲名称。我究竟做错了什么?(它不是 MainActivity,它是加载屏幕)这是我的服务:
class MediaService : Service() {
private val binder = MediaBinder()
private var list = arrayOf(
R.raw.1, R.raw.2, R.raw.3, R.raw.4)
private lateinit var mediaPlayer: MediaPlayer
private val mGenerator = Random()
val randomNumber: Int
get() = list.get(mGenerator.nextInt(4))
override fun onCreate() {
super.onCreate()
mediaPlayer = MediaPlayer.create(applicationContext, randomNumber)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
mediaPlayer.start()
Log.d(LOGCAT, "Media Player started!")
if (!mediaPlayer.isLooping) {
Log.d(LOGCAT, "Problem in Playing Audio")
}
return START_STICKY
}
override fun onDestroy() {
mediaPlayer.stop()
mediaPlayer.release()
}
inner class MediaBinder : Binder() {
// Return this instance of LocalService so clients can call public methods
fun getService(): MediaService = this@MediaService
}
override fun onBind(intent: Intent): IBinder {
return binder
}
}
这是我的活动:
class MyActivity : AppCompatActivity() {
private lateinit var mService: MediaService
private var mBound: Boolean = false
private val connection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
val binder = service as MediaService.MediaBinder
mService = binder.getService()
mBound = true
}
override fun onServiceDisconnected(arg0: ComponentName) {
mBound = false
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(view)
var fragment = LayoutProcessingFragment()
if (mBound) {
when (mService.randomNumber) {
R.1
-> {
fragment.binding.textGroupName.text = "1"
}
R.raw.2
-> {
fragment.binding.textGroupName.text = "2"
}
R.raw.3
-> {
fragment.binding.textGroupName.text = "3"
}
R.raw.4
-> {
fragment.binding.textGroupName.text = "4"
}
}
}
playAudio(view)
}
fun playAudio(view: View?) {
val objIntent = Intent(this, MediaService::class.java)
startService(objIntent)
}
override fun onStart() {
super.onStart()
// Bind to LocalService
Intent(this, MediaService::class.java).also { intent ->
bindService(intent, connection, Context.BIND_AUTO_CREATE)
}
}
override fun onStop() {
super.onStop()
unbindService(connection)
mBound = false
}
}