我知道现在分享答案为时已晚,但我会把我的两分钱放在这里,因为它非常非常重要。我浪费了两天的时间来解决这个问题。我尝试了此处提供的所有建议解决方案,但似乎没有任何效果。以下是我在以下步骤中实施的解决方案:
步骤#01
像你一样创建你的前台服务,并在清单中相应地注册它。出于示例目的,我正在分享服务示例。
class MyService : Service() {
private var wakeLock: PowerManager.WakeLock? = null
override fun onBind(intent: Intent): IBinder? {
Log.d(tag!!, "Some component want to bind with the service")
// We don't provide binding, so return null
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d(tag!!, "onStartCommand executed with startId: $startId")
// by returning this we make sure the service is restarted if the system kills the service
return START_STICKY
}
override fun onCreate() {
super.onCreate()
Log.d(tag!!, "The service has been created".toUpperCase(Locale.ROOT))
startForeground(1, NotificationUtils.createNotification(this))
acquireLock()
}
override fun onDestroy() {
super.onDestroy()
Log.d(tag!!, "The service has been destroyed".toUpperCase(Locale.ROOT))
Toast.makeText(this, "Service destroyed", Toast.LENGTH_SHORT).show()
}
override fun onTaskRemoved(rootIntent: Intent?) {
Log.d(tag!!, "onTaskRemoved")
val restartServiceIntent = Intent(applicationContext, this.javaClass)
restartServiceIntent.setPackage(packageName)
val restartServicePendingIntent = PendingIntent.getService(applicationContext, 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT)
val alarmService = applicationContext.getSystemService(ALARM_SERVICE) as AlarmManager
alarmService[AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000] = restartServicePendingIntent
super.onTaskRemoved(rootIntent)
}
@SuppressLint("WakelockTimeout")
private fun acquireLock() {
// we need this lock so our service gets not affected by Doze Mode
wakeLock =
(getSystemService(Context.POWER_SERVICE) as PowerManager).run {
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyService::lock").apply {
acquire()
}
}
}
}
注意:我已经介绍了所有可能的用例来重新启动服务,以防它被操作系统杀死。如果用户重新启动手机,还剩下一件事。这种情况可以很容易地通过其他 stackoverflow 答案找到。在广播中只需要启动服务。
步骤#02
提出申请并在清单中注册。并在您的应用程序类中添加以下代码行。
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
val receiver = ComponentName(this, MyService::class.java)
val pm = packageManager
pm.setComponentEnabledSetting(
receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP
)
}
}
这里,MyService 是组件名称,可以是您已经在应用中使用的Service 或Broadcast Receiver。就我而言,我尝试使用 Android 服务
现在,是时候在 Manifest 文件中注册这个 Application 类了。打开清单文件并在应用程序标记中使用属性 name 并放置刚刚创建的应用程序类名称 MyApplication。
步骤#03
没有第三步。你完成了。您只需安装 apk,这样即使应用程序被杀死,Service 也不会被杀死。我在 Vivo 设备上测试了上述解决方案,它有效
注意:如果上述解决方案不起作用,请检查清单文件中的 allowBackup 属性,如果您在清单文件中发现此属性,只需将其删除并卸载应用程序,然后再安装应用程序它肯定会起作用,然后您可以再次设置该属性。