Android的:在后台运行的服务永远 [英] Android: Running service in background forever
问题描述
我不知道为什么,但我的服务(开始使用startService(意向...))保持关闭了一段时间。我希望我的服务,以检查每2分钟WiFiSLAM的位置,因此TimerTask的是在服务运行。我意识到,我的服务被关闭后,应用程序被关闭(的onDestroy)和屏幕关闭。
I don't know why, but my Service ( started with startService(Intent...) ) keeps closing after a while. I want my Service to check every 2 minutes the position with WiFiSLAM, therefore a TimerTask is running in the Service. I realized that my Service is shutting down after the App is closed (onDestroy) and the screen turned off.
我读过有关WakeLock,并试图这样的:
I've read about the WakeLock and tried this:
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wakeLock.acquire();
但它仍然无法正常工作。我不知道该怎么办。我只是想有我的WiFi定位框架的更新在后台的位置每两分钟。
But it still does not work. I don't know what to do. I just want to have my Wifi Positioning Framework to update the position in the background every two minutes.
我还设置onStartCommand(),以START_STICKY的返回值。也许它是在后台运行,但我不能看到日志中的LogCat中当它运行一段时间,这给了我预示着,indoorLocationManager仍在追赶新的岗位。
I also set the return value of onStartCommand() to START_STICKY. Maybe it is running in the background, but I can't see the Logs in the LogCat when it is running for a while, which gives me signals that the indoorLocationManager is still catching new positions.
有人有一个想法?
推荐答案
Android的自动杀死在后台运行很长时间(30分钟〜1小时)。
Android automatically kills applications running in background for long periods (between 30 minutes and 1 hour).
要prevent这是设置您的服务作为前台服务
的唯一方法。
The only way to prevent this is setting your service as foreground service
.
要做到这一点,您使用以下命令:
To do that, you use the following:
startForeground(messgae, notification);
这将显示一个Permanente的通知,通知您的服务正在运行的用户。
This will show a permanente notification informing the user that your service is running.
其他的选项,是使用 AlarmManager
来启动 IntentService
每2分钟。
Other option, is to use AlarmManager
to start an IntentService
every 2 minutes.
问候。
这篇关于Android的:在后台运行的服务永远的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!