工作经理完全取决于制造商,一些制造商或者您也可以说具有库存ROM的设备允许工作经理正常工作,但是有些设备制造商(“中国ROM”)在清除时非常激进后台应用程序,它们甚至杀死了工作管理器,但是,Google 正试图通过与 OEM 的对话使工作管理器在所有设备上正常工作。
到目前为止,如果您真的想在后台运行任何东西,您可以在小米和其他一些设备中打开自动启动选项,或者您也可以在通知托盘中显示通知,使应用程序在前台运行。您可以检查应用程序是否仍在后台运行,如果没有,您可以重新启动它。
if (!isServiceRunning(this, MyService::class.java)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(Intent(this, MyService::class.java))
} else {
startService(Intent(this, MyService::class.java))
}
}
private fun isServiceRunning(context: Context, serviceClass: Class<*>): Boolean {
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val services = activityManager.getRunningServices(Integer.MAX_VALUE)
if (services != null) {
for (i in services.indices) {
if (serviceClass.name == services[i].service.className && services[i].pid != 0) {
return true
}
}
}
return false
}
val am = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val pi = PendingIntent.getBroadcast(
applicationContext,
34,
Intent(this, MyBroadcastReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)
am.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, pi)
最后在广播接收器中。
override fun onReceive(context: Context?, intent: Intent?) {
Handler(Looper.getMainLooper()).post {
if (!isServiceRunning(context!!, MyService::class.java)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(Intent(context, MyService::class.java))
} else {
context.startService(Intent(context, MyService::class.java))
}
}
val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val pi = PendingIntent.getBroadcast(
context, 34, Intent(context, MyBroadcastReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)
am.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, pi)
}
}