即使关闭Activity,也要保持Android服务运行 [英] Keep Android service running even after Activity is closed
问题描述
我正在构建其中的SOS应用程序之一。每当设备震动超过阈值(通过加速度计检测到)时,我都会显示 Toast
(截至目前)
I am building one of those SOS apps. Whenever the device is shaken above a threshold value (detected through accelerometer), I am showing a Toast
(as of now)
1)应用启动。用户提供姓名,电子邮件等。然后在最后一个屏幕上单击完成
。
1) App is launched. User gives name, email, etc.. and clicks finish
on last screen.
2)服务
已启动,不断监听震动。
2) Service
is started which keeps listening for shake.
3)如果应用程序正在运行,它将正确检测到震动。
3) It detects the shake correctly if the App is running.
4)如果我关闭该应用程序(活动
),该服务将随之消失。
4) If I close the app (the activity
), the service gets killed along with it.
即使应用已关闭,如何保持服务
仍在运行,以便它可以听到来自背景的震动? (这就是该应用程序的全部目的)
How do I keep the service
running even if app is closed, so that it can listen to shakes from background? (That's the whole purpose of this app)
[1。我在 onStartCommand $ c中返回了 START_STICKY $ c>
[1.I am returning START_STICKY in onStartCommand
-
我也尝试过使用
BroadcasterReciever
将会通过接收来自onTaskRemoved
的广播来重新启动服务,我正在ASUS Xenfone Max上进行测试, 棉花糖操作系统
]
I am testing on ASUS Xenfone Max, Marshmallow OS ]
推荐答案
您有两个选择:
- 将服务作为前台服务启动(使用
startForeground(int id,Notification notification)
:文档。但是在这种情况下,只要您的服务正在运行,您就必须在通知栏中显示通知。 - 为服务使用单独的进程,将清单添加到您的进程中
android:process =:nameofyourprocess
- Start your service as foreground service (with
startForeground(int id, Notification notification)
: docs. But in this case you will have to show Notification in notification tray for as long as your service is running - Use separate process for your service adding in manifest to your process
android:process=":nameofyourprocess"
这篇关于即使关闭Activity,也要保持Android服务运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!