android - 小米设备停止前台服务

标签 android android-service foreground-service xiaomi

我们有一个应用程序几乎永远运行前台服务,同时在系统托盘上使用通知,这是正常的初始化。 该应用程序仅依赖于此服务。在我们测试的每台设备上,即使任务被删除,该服务仍会继续运行,但在小米设备上,从最近滑动后,它突然停止,然后再次启动,具体取决于关于 ActivityManager 如何决定重新打开服务。我们从小米设备(本例中为小米 MI9)获取日志,例如:

安排崩溃服务的重启:com.example.myapp/.MyService 在 1000 毫秒内

这不应该发生,但确实发生了。并且每次我们从最近打开和关闭应用程序时,1000ms 部分不断增加到4000ms、16000ms、64000ms 等等。我认为它没有限制,64 秒对于重新启动对应用程序至关重要的前台服务来说已经太长了。所以,我正在寻找将我们的应用程序添加为异常或其他东西的方法,但我唯一找到的是:https://dontkillmyapp.com/xiaomi

如果应用程序被最近屏幕上的 X 按钮杀死,那么情况会更糟,因为我注意到设备会杀死所有服务并安排它们在 10 秒间隔内重新启动。我认为我们的应用程序计划在 3 小时后开始,这破坏了该应用程序的目的。

我们当前使用的解决方案是警告用户此问题并重定向到此链接,以便将我们的应用程序添加到异常(exception)情况、启用自动启动等。但是,我们知道几乎没有人会这样做,因此我们正在寻找可以通过编程实现的解决方案。

一小段代码演示了我们如何注册服务以显示以及如何启动它。 (演示比原来简单,但描述了主要逻辑。)

list 部分:

<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;
}

我认为一切都已正确完成,因为这只发生在小米设备上,但我们找不到让这项服务保持活跃的解决方案。还有其他人遇到同样的事情吗?我们应该如何进行才能使我们的服务不至于消亡?感谢所有帮助。

最佳答案

转到设置->权限->自动启动,然后选择您的应用

关于android - 小米设备停止前台服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57976116/

相关文章:

Android keystore 密码更改

java - 检查设备是否为双核

java - 需要将 AssetInputStream 转换为 FileInputStream

android - 使用 android Studio 的带有 TextView 和 EditText 的 TableLayout

android - 从 android 中的信使/处理程序获取待处理消息的列表

android - START_REDELIVER_INTENT 如何处理多个 Intent?

android - 如何从广播接收器启动前台服务?

android - 工作线程过早结束

android - 检查 Android OREO 中的前台服务是否正在运行

java - 使用 BroadcastReceiver 更新 ProgressBar