android 当 运行 更多其他应用时后台服务停止

android background service stopping when running more other apps

我目前正在尝试制作一个永不结束(在 freeze/stopped/swiped/killed 等时重新启动)的 android 应用程序以用于特定用途。

所以我使用后台服务和 onTaskRemoved() 在从最近的应用程序列表中滑出时重新启动服务。还 START_STICKY 保留它 运行 背景。

当没有太多新应用时,我的应用可以很好地响应我的声音(它显示吐司)运行。但是当时间过得很快或者上面有3~4个运行个应用程序时,它就会卡住(不响应我的声音)。

有没有办法让我的应用程序总是 运行 在其他应用程序之上(比如总是在按下主页按钮几秒钟时显示的最近应用程序列表的顶部)或者只是简单地重新启动应用程序是否冻结?

请帮帮我。我知道尝试创建一个永无止境的应用程序听起来很奇怪,但如果你能帮助我,那将对我的项目有很大帮助。

谢谢:)

对于android不要停止你可以调用startForeground()的服务

However, some services will be missed by the user if they mysteriously vanish. For example, the default music player application that ships with Android uses a service for the actual music playback. That way, the user can listen to music while continuing to use their phone for other purposes. The service only stops when the user goes in and presses the stop button in the music player activity. If that service were to be shut down unexpectedly, the user might wonder what is wrong.

Services like this can declare themselves as being part of the "foreground". This will cause their priority to rise and make them less likely to be bumped out of memory. The trade-off is that the service has to maintain a Notification, so the user knows that this service is claiming part of the foreground. And, ideally, that Notification provides an easy path back to some activity where the user can stop the service.

To do this, in onCreate() of your service (or wherever else in the service's life it would make sense), call startForeground(). This takes a Notification and a locally-unique integer, just like the notify() method on NotificationManager. It causes the Notification to appear and moves the service into foreground priority. Later on, you can call stopForeground() to return to normal priority.