最近在使用android 4.1系统的时候,发现在手机休眠一段时间后(1-2小时),后台运行的服务被强行kill掉,有可能是系统回收内存的一种机制,要想避免这种情况可以通过startForeground让服务前台运行,当stopservice()的时候通过stopForeground()去掉。
Running a Service in the Foreground
A foreground service is a service that's considered to be something the user is actively aware of and thus not a candidate for the system to kill when low on memory. A foreground service must provide a notification for the status bar, which is placed under the "Ongoing" heading, which means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.
For example, a music player that plays music from a service should be set to run in the foreground, because the user is explicitly aware of its operation. The notification in the status bar might indicate the current song and allow the user to launch an activity to interact with the music player.
To request that your service run in the foreground, call startForeground(). This method takes two parameters: an integer that uniquely identifies the notification and the Notification for the status bar. For example:

本文介绍了Android中如何使用startForeground()使服务保持前台运行,以防止系统因内存回收而杀死服务。当服务在前台运行时,需要提供一个状态栏通知。stopForeground()用于移除服务的前台状态,但不会停止服务本身。停止服务时,前台通知也会被移除。在Android 2.0之前,需要使用不同方法来实现兼容。

3291

被折叠的 条评论
为什么被折叠?



