android服务运行在单独的线程上
我有一个使用广播接收器在启动时启动的应用程序,我也有一个活动和一个进程,因为该服务必须始终在后台运行,我使用 android:process 清单标记在它自己的进程上启动该服务。
用户界面仅用于演示需求,我希望用户即使活动不活动也能够运行该服务。
我正在使用这个额外的参数启动服务:
intent.putExtra(Intent.EXTRA_DONT_KILL_APP, true);
问题是,当我按下后退按钮或主页按钮时,会调用活动的 on destroy 方法,并且该服务虽然看起来正在运行(它出现在任务管理器上),但其行为并不像假设,它应该连接到网络并发送一些数据,但每隔 X 次使用计时器任务,但该任务永远不会触发,因此数据永远不会发送。
I have an application that starts on boot using a broadcast receiver, also I have an activity and a process, because the service must run always on the background I am starting the service on it's own process using the android:process manifest tag.
The ui is only for presentational needs and I would like the user to be able to run the service even if the activity is not active.
I am starting the service using this extra parameter:
intent.putExtra(Intent.EXTRA_DONT_KILL_APP, true);
the problem is that when I press the back button or the home button the activity's on destroy method is called and the service although seems its running (it appears on the task manager) its not behaving as supposed, it should connect to the net and send some data but every X time using an timer task but the task never fires so the data are never send.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请不要这样做。对于初学者来说,这是不可能的,因为 Android 会杀掉你,用户也会杀掉你。考虑到您当前的实现浪费了多少内存,两者都会试图更快地杀死您。
请也不要这样做。你浪费了内存,却没有任何好处。您不需要为此服务单独的流程。
该参数不会执行您认为的操作。它不与启动服务一起使用。
步骤#1:摆脱现有的服务。
步骤#2:使用
AlarmManager
和WakefulIntentService
。安排一个警报(也许使用您的启动时间接收器)“每 X 次”被调用。让WakefulIntentService
“连接到网络并发送一些数据”。Please don't do that. For starters, it is impossible, since Android will kill you off, and users will kill you off. Considering how much RAM you are wasting with your current implementation, both will attempt to kill you off much more quickly.
Please don't do that either. You are wasting RAM to no benefit. You do not need a separate process for this service.
That parameter does not do what you think it does. It is not used with starting services.
Step #1: Get rid of your existing service.
Step #2: Use
AlarmManager
and aWakefulIntentService
. Schedule an alarm (perhaps using your boot-time receiver) to be invoked "every X time". Have theWakefulIntentService
"connect to the net and send some data".我完全同意CommonsWare的回答。但是,如果您真的想用另一个无用的服务来打扰用户,该服务位于背景中,只是在吃内存,您可以使用以下内容:
在您的活动中:
在您的服务中:
再次,请不要只是为了定期执行某些操作而这样做。请使用警报管理器!
I fully agree with CommonsWare's answer. But, if you really want to bother users with yet-another-useless-service-which-sits-in-the-background-just-eating-memory you could use the following:
In your activity:
In your service:
Again, please DO NOT do this just to execute some action periodically. PLEASE use the AlarmManager!