安卓后台服务
我正在阅读文档,花的时间越多,我就越困惑什么是完成我想做的事情的最简单方法。我想编写一个简单的服务,它从按钮 onClick 开始并绑定到活动。当活动关闭并稍后再次启动时(不仅仅是重新启动!),我想检查服务是否已经在运行并绑定到它。我该怎么做?
谢谢
I'm reading through the docs and the more time I spend I get more confused what's the easiest way to accomplish what I'm trying to do. I want to write a simple Service, which starts at button onClick and binds to the activity. And when the activity is closed and started again later (not only restarted!), I want to check whether the service is already running and bind to it. How do I do it?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,我认为你只需要使用 AsyncTask
希望这有帮助
In that Scenario I think you only need to use AsyncTask
hope this helps
要在 android 中执行服务到活动的实际绑定,您需要扩展 Service 类并将服务绑定到您的活动(并且可能使用 Android 的 AIDL 来执行活动和服务之间的通信)。然而,在您的示例中,听起来您只需在活动中使用单独的线程就可以逃脱惩罚。使用可运行任务或 AsyncTask。用户单击触发 onClick 的按钮后,将应用程序中的静态布尔值设置为 true。然后,在重新进入活动时,只需检查该布尔值是否为真,如果为真,则再次触发线程。
To perform actual binding of services to activities in android, you'll need to extend the Service class and bind the service to your activity ( and possibly use Android's AIDL to perform communication between the activity & service). However, in your example, is sounds like you could get away with just using a separate thread within your activity. Use either a runnable or an AsyncTask. Once the user clicks the button that fire's the onClick, set a static boolean within your application to true. Then, upon re-entry into the activity, simply check that boolean for true and, if true, fire off the thread again.