在 Android 的 Activity 中停止与 ServiceConnection 的服务绑定的最佳方法?
我有一个服务通过 ServiceConnection 绑定在我的 Activity 中。 该服务在创建 Activity 时启动,并在我的 BroadcastReceiver 类中停止,并且运行良好。现在,我想在一段时间后停止服务。在我的服务类中尝试 TimerTask,但似乎无法正常工作。
任何建议或解决方案将不胜感激。
谢谢。
I have a Service that is bind in my Activity with a ServiceConnection.
The Service starts when the Activity is created and stops in my BroadcastReceiver class and works great. Now, I will like to stop the Service after a give period. Being trying TimerTask in my Service class, but don't seems to be working correctly.
Any suggestion or solutions would be kindly appreciated.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
计时器也被视为独立的线程。因此当您尝试停止服务时,上下文可能会更改。我的解决方案是获取当前服务的 Pid 并使用 Pid 终止该服务。 android:process 属性将在 androidmanifest.xml 中指定。
进程 process = Runtime.getRuntime().exec("kill pid");
输入流 = process.getInputStream();
这段代码工作正常。尝试一次
Timer also treated as independent Thread.so Context might be changed when you are trying to stop the Service.My Solution is get the Pid of Current service and kill the service using the Pid. android:process attribute will be specified in androidmanifest.xml.
Process process = Runtime.getRuntime().exec("kill pid");
InputStream is = process.getInputStream();
this code works fine . try it once
在您的应用程序中声明静态:
在创建应用程序时为服务分配一个新的 Intent 并绑定到 local_Intent:
记住对 local_Intent 的分配,因为 local_Intent 是静态的
当您想在您的应用程序中启动服务时
当您想在您的应用程序中停止服务时
Declare a static in your App:
On create of the App assign a new Intent for the service and bind to local_Intent:
The assignment to local_Intent is remembered because local_Intent is static
When you want to start the service in your App
When you want to stop the service in your App