安卓Forground服务停止时,应用程序是关闭的

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

我正在启动一个后台服务,在后台接收数据,所以我使用了android foreground服务,该服务在一些手机(MI A2 Stock Android)中完美地工作,但在一些手机上,当我从后台托盘中删除应用程序时,该服务被破坏。

class MyService : Service() {
    private val CHANNEL_ID = "ForegroundService"

    companion object {
        fun stopService(context: Context) {
            val stopIntent = Intent(context, MyService::class.java)
            context.stopService(stopIntent)
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // I get some data from intent 
        // My code which runs in the background

        createNotificationChannel()
        val notificationIntent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this,
            0, notificationIntent, 0
        )

        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("App is syncing")
            .setContentText("")
            .setPriority(2)
            .setSmallIcon(android.R.drawable.ic_dialog_alert)
            .setContentIntent(pendingIntent)
            .build()
        startForeground(190, notification)
        return START_NOT_STICKY
    }

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

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val serviceChannel = NotificationChannel(
                CHANNEL_ID, "Foreground Service Channel",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            val manager = getSystemService(NotificationManager::class.java)
            manager!!.createNotificationChannel(serviceChannel)
        }
    }
}

我是这样启动服务的

val serviceIntent = Intent(this, MyService::class.java)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(serviceIntent)
        } else {
            startService(serviceIntent)
        }

因此,我的问题是如何使我的服务运行,即使当APP从后台托盘中删除。

android kotlin service background-service
1个回答
0
投票

做这些事情

1) 在你的服务类中覆盖这个方法,当应用程序关闭时重新启动服务,复制并粘贴这个方法。

override fun onTaskRemoved(rootIntent: Intent?) {
    val restartServiceIntent = Intent(applicationContext, this.javaClass)
    restartServiceIntent.setPackage(packageName)
    val restartServicePendingIntent = PendingIntent.getService(
        applicationContext,
        1,
        restartServiceIntent,
        PendingIntent.FLAG_ONE_SHOT
    )
    val alarmService =
        applicationContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager
    alarmService[AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000] =
        restartServicePendingIntent
    super.onTaskRemoved(rootIntent)
}

2)改变这个 START_NOT_STICKYSTART_STICKY

3) 要求用户在设置中启用自动运行权限,这个功能在迷你设备、vivo、华为和oppo等自定义操作系统中都有提供。

4) 你忘记了在设备启动时重启服务,比如你需要在设备重启时使用广播接收器来重启服务。

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