本文共 2482 字,大约阅读时间需要 8 分钟。
package com.lyr.myapplication.serviceimport android.app.NotificationChannelimport android.app.NotificationManagerimport android.app.PendingIntentimport android.content.Contextimport android.content.Intentimport android.os.Binderimport android.os.Buildimport android.os.IBinderimport android.util.Logimport androidx.core.app.NotificationCompatimport androidx.lifecycle.LifecycleServiceimport androidx.lifecycle.MutableLiveDataimport androidx.lifecycle.lifecycleScopeimport com.lyr.myapplication.ExampleActivityimport com.lyr.myapplication.Rimport kotlinx.coroutines.delayimport kotlinx.coroutines.launchclass ExampleService : LifecycleService() { val number: MutableLiveData = 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) } }}
转载地址:http://hzyzi.baihongyu.com/