我有一个服务被定义为:
public class SleepAccelerometerService extends Service implements SensorEventListener
基本上,我正在制作一个应用程序,用于在用户将手机/设备放在床上 sleep 时出于各种原因监控加速度计 Activity 。这是一项长期运行的服务,不得在夜间终止。根据夜间发生的后台应用程序和周期性进程的数量,android 有时会杀死我的进程,从而结束我的服务。示例:
10-04 03:27:41.673: INFO/ActivityManager(1269): Process com.androsz.electricsleep (pid 16223) has died.
10-04 03:27:41.681: INFO/WindowManager(1269): WIN DEATH: Window{45509f98 com.androsz.electricsleep/com.androsz.electricsleep.ui.SleepActivity paused=false}
我不想强制用户在我的应用中使用“SleepActivity”或其他一些 Activity 作为前台。我不能让我的服务定期运行,因为它不断拦截 onSensorChanged。
有什么建议吗?源代码在这里:http://code.google.com/p/electricsleep/
最佳答案
对于 Android 2.0 或更高版本,您可以使用 startForeground()
method在前台启动您的服务。
documentation says the following :
A started service can use the
startForeground(int, Notification)
API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)
主要用于当终止服务会对用户造成干扰时,例如杀死音乐播放器服务将停止音乐播放。
您需要为方法提供一个 Notification
,该方法显示在 Ongoing 部分的通知栏中。
关于Android:保持后台服务活着(防止进程死亡),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3856767/