首先,创建一个前台服务来管理音乐播放:
class MusicService : Service() {
override fun onCreate() {
super.onCreate()
createNotificationChannel()
startForeground(1, createNotification())
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
"music_channel",
"Music Channel",
NotificationManager.IMPORTANCE_LOW
)
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(channel)
}
}
private fun createNotification(): Notification {
return NotificationCompat.Builder(this, "music_channel")
.setContentTitle("Music Player")
.setContentText("Playing music")
.setSmallIcon(R.drawable.ic_music_note)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.build()
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
}
在你的 Activity
中启动前台服务:
val intent = Intent(this, MusicService::class.java)
startService(intent)
你可以创建一个自定义通知布局来控制音乐播放:
private fun createNotification(): Notification {
val remoteViews = RemoteViews(packageName, R.layout.notification_layout)
val playIntent = Intent(this, MusicService::class.java).apply {
action = "ACTION_PLAY"
}
val playPendingIntent = PendingIntent.getService(this, 0, playIntent, 0)
remoteViews.setOnClickPendingIntent(R.id.play_button, playPendingIntent)
return NotificationCompat.Builder(this, "music_channel")
.setContent(remoteViews)
.setSmallIcon(R.drawable.ic_music_note)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.build()
}
在 MusicService
中处理广播接收器来控制播放、暂停等操作:
class MusicService : Service() {
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
when (intent?.action) {
"ACTION_PLAY" -> {
// 处理播放操作
}
"ACTION_PAUSE" -> {
// 处理暂停操作
}
}
}
}
override fun onCreate() {
super.onCreate()
createNotificationChannel()
startForeground(1, createNotification())
registerReceiver(receiver, IntentFilter().apply {
addAction("ACTION_PLAY")
addAction("ACTION_PAUSE")
})
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(receiver)
}
// 其他代码...
}
确保通知在锁屏时显示:
private fun createNotification(): Notification {
return NotificationCompat.Builder(this, "music_channel")
.setContentTitle("Music Player")
.setContentText("Playing music")
.setSmallIcon(R.drawable.ic_music_note)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC) // 锁屏时显示
.build()
}