Android:屏幕关闭后服务无法使用

问题描述 投票:0回答:1

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

服务代码:

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
    }
}

谢谢您的帮助!

android service notifications
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.