Android Service 适配 8.1+

2019-05-30  本文已影响0人  _发强

整理一下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 方法中。

上一篇下一篇

猜你喜欢

热点阅读