android#完结#绑定前台服务


package com.lyr.myapplication.service


import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import com.lyr.myapplication.ExampleActivity
import com.lyr.myapplication.R
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class ExampleService : LifecycleService() {
     val number: MutableLiveData<Int> = MutableLiveData(0)
    override fun onCreate() {
        super.onCreate()
        //创建通道
        createChannel()
        //设置 点击通知,跳入程序
        val pendinigIntent = PendingIntent.getActivity(this,0,Intent(this,ExampleActivity::class.java),0)
        val notification = NotificationCompat.Builder(this,ID)
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setContentTitle("后台通知吼吼")
            .setContentText("123 记得喝牛奶")
            .setContentIntent(pendinigIntent)
            .build()
        //后台一直运行,不停止
        startForeground(1,notification)

        Log.i("xxx", "开启服务")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        var number = 1
        lifecycleScope.launch{
            while (true) {
                delay(1_000)
                Log.d("xx","${++number}")
            }
        }


        return super.onStartCommand(intent, flags, startId)

    }

    inner class ExampleBinder : Binder() {
        val service:ExampleService = this@ExampleService
    }

    override fun onBind(intent: Intent): IBinder {
        super.onBind(intent)

        lifecycleScope.launch{
            while (true) {
                delay(1_000)
                number.value = number.value?.plus(1)
            }

        }
        return ExampleBinder()
    }

    val ID = "Application_channel_11"
    fun createChannel() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            val number = "Application_channel_11"
            val channel = NotificationChannel(ID,"channel test",NotificationManager.IMPORTANCE_DEFAULT)
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }


    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值