android四大组件之Service(二):前台服务

Android前台服务是指可以与用户交互的服务,典型示例是音乐播放器,用户可以通过开发者在通知栏设置的自定义通知来操作播放暂停上一首下一首等操作。前台服务创建示例:

class ForegroundService : Service() {

    override fun onBind(intent: Intent) = MyBinder()

    override fun onCreate() {
        super.onCreate()
        setForeground()

        Log.d(javaClass.simpleName, "onCreate......")
    }

    
    private fun setForeground() {
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val builder = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            var channel = manager.getNotificationChannel("MyChannel")
            if (channel == null) {
                val importance = NotificationManager.IMPORTANCE_DEFAULT
                channel = NotificationChannel("MyChannel", "MyChannel", importance)
                manager.createNotificationChannel(channel)
            }
            Notification.Builder(this, channel.id)
        } else {
            Notification.Builder(this)
        }

        val intent = Intent(this, MainActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT or Intent.FLAG_ACTIVITY_SINGLE_TOP
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
        
        builder.setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("这是标题")
            .setContentText("这是内容文字")
            .setContentIntent(pendingIntent)
        
        val notification: Notification = builder.build()
        manager.notify(0, notification)
        startForeground(0, notification)
    }

    inner class MyBinder : Binder() {
        fun getService(): ForegroundService = this@ForegroundService
    }
}

前台服务的优先级比后台服务高,系统不会轻易销毁前台服务。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值