如何解决想要在点击通知时停止前台服务
我正在尝试使用前台服务进行通知,并且我在下面提供了媒体播放器,并且它处于循环中。
现在我想在点击通知时停止重复播放器/服务 我的服务类就像
我已经在通知 Intent 和主 Activity 中提供了 getExtra 和 PutExtra,这样有效吗?
`var player: MediaPlayer?=null
val CHANNEL_ID = "ForegroundServiceChannel"
override fun onStartCommand(intent: Intent?,flags: Int,startId: Int): Int {
val input = intent!!.getStringExtra("inputExtra")
createNotificationChannel()
val notificationIntent = Intent(this,MainActivity::class.java)
notificationIntent.putExtra("cancel",true)
val pendingIntent = PendingIntent.getActivity(
this,notificationIntent,0
)
player= MediaPlayer.create(this,Settings.System.DEFAULT_RINGTONE_URI)
player?.isLooping=true
player?.start()
val notification = NotificationCompat.Builder(this,CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_baseline_access_alarm_24)
.setContentIntent(pendingIntent)
.build()
startForeground(1,notification)
return START_STICKY
}
override fun onDestroy() {
super.onDestroy()
player?.stop()
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val serviceChannel = NotificationChannel(
CHANNEL_ID,"Foreground Service Channel",NotificationManager.IMPORTANCE_DEFAULT
)
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(serviceChannel)
}
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
} `
我的主要活动类就像
` val playBtn by lazy { findViewById<Button>(R.id.playBtn) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
playBtn.setOnClickListener(object:View.OnClickListener {
override fun onClick(v: View?) {
//val serviceIntent = Intent(this@MainActivity,androidServ::class.java);
// serviceIntent.putExtra("cancel","Foreground Service Example in Android")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(Intent(this@MainActivity,androidServ::class.java))
}
}
})
stopService(this)
}
private fun stopService(context: MainActivity) {
val serviceIntent = Intent(context,androidServ::class.java)
serviceIntent.getStringExtra("cancel")
val an =androidServ()
an.player?.stop()
}`
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。