我知道现在分享答案有点晚了,但我还是想加入我的两分钱,因为这非常非常重要。我浪费了2天时间来解决这个问题。我尝试了这里提供的所有建议解决方案,但似乎没有任何东西能够工作。以下是我按照以下步骤实施的解决方案:
步骤#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")
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d(tag!!, "onStartCommand executed with startId: $startId")
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() {
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 是组件名称,它可以是你的应用程序中已经在使用的服务或广播接收器。在我的案例中,我使用了Android服务。
现在,是时候在清单文件中注册这个应用程序类了。打开清单文件,在application标签中使用属性name,并放置你刚创建的应用程序类名MyApplication。
第三步
没有第三步。完成了。你只需要安装apk,这样即使应用程序被杀死,服务也不会停止运行。我在Vivo设备上测试了以上解决方案,它可以正常工作。
注意:如果以上解决方案不起作用,请检查清单文件中的allowBackup属性,如果在清单文件中找到此属性,请将其删除,然后卸载应用程序并重新安装应用程序,它一定会起作用,然后你可以再设置该属性。