如何引用使用 Intent / startService 创建的对象
如果我在应用程序的 onCreate 中创建一个服务,如下所示:
Intent srv = new Intent( this, MyService.class );
startService( srv );
如何获取对服务对象的引用以及服务对象如何引用启动它的应用程序?
(是的,我已在 AndroidManifest 中列出了该服务)。
If I create a service in my app's onCreate
like this:
Intent srv = new Intent( this, MyService.class );
startService( srv );
how do I get a reference to the service object and how does the service object reference the app which launched it?
(Yes, I have listed the service in my AndroidManifest).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有几种方法可以处理这个问题。您可以绑定到服务(bindService),您将通过 IBinder 接口回调。
另一种方法是继续使用不同的意图数据调用 startService() 作为向服务发送消息的方式,其中意图额外数据包含消息细节。
最后,如果您知道服务位于同一进程中,则可以共享某些静态内存中的服务实例。
There are a few ways to handle this. You can bind to the service (bindService) where you will be called back with an IBinder interface.
Another approach is to just keep calling startService() with different intent data as a way of messaging to the service, with intent extra data containing message specifics.
Finally, if you know the service is in the same process, you can share the service instance in some static memory.
构建Service
首先,我们需要在AndroidManifest.xml 文件中创建Service。请记住,您在代码中创建的每个 Activity、Service、Content Provider 都需要在 Manifest 中创建一个引用,如果没有,应用程序将无法识别它。
在代码中,我们需要创建一个从“Service”扩展的类,
这是创建服务的一种方法,还有其他方法,或者我用来使用它们的方法。在这里,我们创建一个计时器,每 X 秒调用一个方法。它会一直运行直到我们停止它。例如,这可用于检查 RSS 源中的更新。 “Timer”类在 startservice 方法中使用,如下所示
其中 INTERVAL 是每次执行 run 方法的时间。
要停止服务,我们可以停止计时器,例如,当应用程序被销毁时(在 onDestroy() 中),
因此,该应用程序将在后台运行......
Building a Service
First of all, we need to create the Service in the AndroidManifest.xml file. Remember, that every Activity, Service, Content Provider you create in the code, you need to create a reference for here, in the Manifest, if not, the application will not recognize it.
In the code, we need to create a class that extends from “Service”
This is a way to create Services, there are others ways, or the way I use to work with them. Here, we create a Timer, that every X seconds, calls to a method. This is running until we stop it. This can be used, for example, to check updates in an RSS feed. The “Timer” class is used in the startservice method like this
Where INTERVAL, is the time, every time the run method is executed.
To stop the service, we can stop the timer, for example, when the application is destroyed (in onDestroy())
So, this application will be running in the background...