Android Service 适配 8.1+

整理一下Android 8.0 以上版本 service 启动相关代码。
在 Service 的 onCreate 方法中添加以下代码:

val id = (System.currentTimeMillis() % 10000).toInt()
        val channelId = getString(R.string.app_name)
        val notification: Notification
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(channelId, channelId, NotificationManager.IMPORTANCE_DEFAULT).apply {
                enableLights(true)
                description = channelId
                setSound(Settings.System.DEFAULT_NOTIFICATION_URI, Notification.AUDIO_ATTRIBUTES_DEFAULT)
            }
            val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            manager.createNotificationChannel(channel)

            notification = NotificationCompat.Builder(this, channelId)
                    .setChannelId(channelId)
                    .setSmallIcon(R.drawable.icon_launcher)
                    .setContentTitle(channelId)
                    .setContentText(channelId + "正在运行")
                    .setAutoCancel(true)
                    .build()

        } else {
            notification = NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.drawable.icon_launcher)
                    .setContentTitle(channelId)
                    .setContentText(channelId + "正在运行")
                    .setAutoCancel(true)
                    .build()
        }
        startForeground(id, notification)

启动调用:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            startForegroundService(Intent(this, NotifyService::class.java))
        } else {
            startService(Intent(this, NotifyService::class.java))
        }

销毁服务:

stopService(Intent(this, NotifyService::class.java))

onCreate 方法只执行一次,逻辑代码写在 onStartCommand 方法中。

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
  //todo 逻辑代码。
  ...
  return super.onStartCommand(intent, flags, startId)
}

如果Service 执行了 onCreate 方法,并且没有被销毁,那么下次再 startServcie 则直接进入 onStartCommond 方法中。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容