Kotlin-ForegroundService前台服务实现及Android O通知代码示例

在本示例中,我们将展示如何使用Kotlin编写一个具有Android O通知的前台服务。首先,我们定义一个MainActivity类,其中包含服务绑定和通知管理功能。为了确保服务在后台运行时不被系统杀死,我们需要在服务中显示一个前台通知。以下是实现代码:

class MainActivity : AppCompatActivity() {
    var myService: MyService? = null
    var isBound = false

    privateval myConnection = object : ServiceConnection {
        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            val binder = service as MyService.LocalBinder
            myService = binder.getService()
            isBound = true
        }

        override fun onServiceDisconnected(className: ComponentName) {
            isBound = false
        }
    }

    override fun onStart() {
        super.onStart()
        val intent = Intent(this, MyService::class.java)
        bindService(intent, myConnection, Context.BIND_AUTO_CREATE)
    }

    override fun onStop() {
        super.onStop()
        if (isBound) {
            unbindService(myConnection)
            isBound = false
        }
    }
}

class MyService : Service() {
    privateval binder = LocalBinder()

    inner class LocalBinder : Binder() {
        fun getService(): MyService = this@MyService
    }

    override fun onBind(intent: Intent): IBinder? {
        return binder
    }

    override fun onCreate() {
        super.onCreate()
        startForegroundService()  // 启动前台服务并显示通知
    }

    private fun startForegroundService() {
        val notificationChannel = NotificationChannel(
            CHANNEL_ID,
            "Foreground Service Channel",
            NotificationManager.IMPORTANCE_DEFAULT
        )
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(notificationChannel)

        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Foreground Service")
            .setContentText("Service is running in the foreground")
            .setSmallIcon(R.drawable.ic_notification)
            .build()

        startForeground(1, notification)
    }
}
zip 文件大小:7.01KB