我们有一个几乎永远运行的应用程序前台服务,同时使用系统托盘上的通知,这是正常的初始化。该应用程序仅依赖于此服务。在我们测试的每台设备上,即使任务被删除,服务也会继续运行,但在小米设备上,从最近的任务滑动后,它突然停止,然后再次启动,具体取决于 ActivityManager 决定如何重新打开服务。我们从小米设备(本例为小米 MI9)获取日志,例如:
Scheduling the restart of the crashed service: com.example.myapp/.MyService in 1000ms
这不应该发生,但它确实发生了。每次我们打开应用程序并从最近的应用程序中关闭它时,1000ms
部分不断增加到4000ms, 16000ms, 64000ms
等等。我不认为它有限制,而且 64 秒对于重新启动对于应用程序至关重要的前台服务来说已经太长了。因此,我正在寻找将我们的应用程序添加为例外或其他内容的方法,但我唯一发现的是:https://dontkillmyapp.com/xiaomi https://dontkillmyapp.com/xiaomi
如果应用程序被杀死X按钮在最近的屏幕上,然后情况更糟,因为我注意到设备杀死了所有服务并安排它们在 10 秒的间隔内重新启动。我认为我们的计划是在 3 小时后启动,这破坏了应用程序的目的。
我们当前使用的解决方案是警告用户此问题并重定向到此链接,以便将我们的应用程序添加到例外,启用自动启动等。但是,我们知道几乎没有人会这样做,因此我们正在寻找一种可以通过编程方式实现的解决方案。
一些代码演示了我们如何将服务注册到清单以及如何启动它。 (演示比原来简单,但描述了主要逻辑。)
清单部分:
<service android:name=".MyService"
android:stopWithTask="false" />
启动服务部分:
// Starts the service as foreground.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
context.startForegroundService(new Intent(context, MyService.class));
else
context.startService(new Intent(context, MyService.class));
发布通知部分:
// Post the notification on both onCreate and
// onStartCommand so we can only hope that
// the app won't throw the unavoidable exception
// which occurs 5 seconds after calling
// Context.startForegroundService().
@Override
public void onCreate()
{
super.onCreate();
// Handles how the notification
// is shown, content is not important.
// Calls startForeground inside.
showNotification();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
showNotification();
// Some other service code that is irrelevant
// Return START_STICKY so we can ensure that if the
// service dies for some reason, it should start back.
return START_STICKY;
}
我认为一切都正确完成,因为这只发生在小米设备上,但我们找不到保持此服务活跃的解决方案。还有其他人经历同样的事情吗?我们应该如何继续我们的服务才不会消亡?感谢您的所有帮助。