Android:萤幕关闭后服务无法运作

时间:2019-12-09 19:03:06

标签: android service notifications

我正在尝试创建服务,该服务将从服务器(定期)获取数据并将通知发送给用户。我几乎实现了我的目标,但是在屏幕关闭时服务停止工作。当我打开手机时,我会收到很多以前的通知。

服务代码:

class MyService: Service() {

    override fun onCreate() {
        super.onCreate()

        val handler = Handler()
        val runnable = object: Runnable {
            override fun run() {
                getDataFromServer()
                handler.postDelayed(this, 1800000)
            }
        }
        handler.post(runnable)
    }

    private fun getDataFromServer() {
        // fetch data

        displayNotification(description)
    }

    private fun displayNotification(description: String) {
        val intent = Intent(this, MainActivity::class.java)

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val notificationId = (0..300).random()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val adminChannelName = "Messages channel"
            val adminChannelDescription = "Notification about new data"

            NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_HIGH).apply {
                description = adminChannelDescription
                enableLights(true)
                lightColor = Color.RED
                enableVibration(true)
                notificationManager.createNotificationChannel(this)
            }
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        val pendingIntent = PendingIntent.getActivity(
            this, 0, intent, PendingIntent.FLAG_ONE_SHOT
        )

        val notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val notificationBuilder = NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
            .setSmallIcon(R.drawable.icon_small)
            .setContentTitle(getText(R.string.notification_new_data_title))
            .setContentText(getString(R.string.notification_new_data_text, description))
            .setAutoCancel(true)
            .setSound(notificationSoundUri)
            .setContentIntent(pendingIntent)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            notificationBuilder.color = ContextCompat.getColor(context, R.color.icon_background)
        }
        notificationManager.notify(notificationId, notificationBuilder.build())
    }

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

谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

尝试使用startForegroundService而不是startService启动服务,无论是否需要后台服务,都可以将Service转换为JobIntentService: https://developer.android.com/reference/androidx/core/app/JobIntentService