Android:保持后台服务处于活动状态(防止进程死亡) [英] Android: keeping a background service alive (preventing process death)

查看:54
本文介绍了Android:保持后台服务处于活动状态(防止进程死亡)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务定义为:

public class SleepAccelerometerService extends Service implements SensorEventListener

本质上,我正在制作一个应用程序,当用户将手机/设备放在床上时,出于各种原因监控加速度计活动.这是一项长期运行的服务,不得在夜间终止.根据夜间发生的后台应用程序和周期性进程的数量,android 有时会终止我的进程,从而终止我的服务.示例:

Essentially, I am making an app that monitors accelerometer activity for various reasons while the user sleeps with his or her phone/device on the bed. This is a long-running service that MUST NOT be killed during the night. Depending on how many background apps and periodic processes occur during the night, android sometimes kills off my process, thereby ending my service. Example:

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"或其他一些活动作为前台.我不能让我的服务定期运行,因为它一直在拦截 onSensorChanged.

I do not want to force the user to have 'SleepActivity' or some other activity in my app as the foreground. I can't have my service run periodically, because it is constantly intercepting onSensorChanged.

有什么建议吗?源代码在这里:http://code.google.com/p/electricsleep/

Any tips? source code is here: http://code.google.com/p/electricsleep/

推荐答案

对于 Android 2.0 或更高版本,您可以使用 startForeground() 方法 在前台启动您的服务.

For Android 2.0 or later you can use the startForeground() method to start your Service in the foreground.

文档如下:

启动的服务可以使用 startForeground(int, Notification) API 将服务置于前台状态,在这种状态下,系统认为它是用户主动意识到的,因此不是内存不足时杀戮的候选者.(理论上仍有可能在当前前台应用程序的极端内存压力下终止服务,但实际上这不应该是一个问题.)

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.)

主要用于终止服务会对用户造成破坏时,例如终止音乐播放器服务会停止音乐播放.

The is primarily intended for when killing the service would be disruptive to the user, e.g. killing a music player service would stop music playing.

您需要为显示在正在进行"部分的通知栏"中的方法提供一个通知.

You'll need to supply a Notification to the method which is displayed in the Notifications Bar in the Ongoing section.

这篇关于Android:保持后台服务处于活动状态(防止进程死亡)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆