如何调用从活动服务的方法呢?方法

2023-09-12 04:37:03 作者:半生浮名

我只是想调用一个本地服务的方法来自我的活动。我怎样才能做到这一点?

I simply want to call methods of a local service from my activity. How can i do that ?

推荐答案

要做到这一点的方法之一是通过定义与的 Android的AIDL 并利用了文件夹子系统进行IPC。有一个伟大的一套在我张贴的链接指令。我会从那里开始,然后张贴在这里,如果您有任何疑问。尽管是pretty的复杂问题(IPC)Android和文件夹这样做使得它pretty的死简单的一个很好的工作(至少上手,我敢肯定,你可以做,如果你想;-))它复杂

One way to do this is by defining an interface with Android's AIDL and making use of the Binder subsystem to perform IPC. There is a great set of instructions at the link I posted. I'd start there and then post here if you have questions. Despite being a pretty complex topic (IPC) Android and the Binder do a really good job of making it pretty dead simple (at least to get started, I'm sure you could make it complicated if you wanted to ;-) )

修改正如在评论中,这是不必要的,如果服务和客户端都在同一个进程中运行。除非你指定,这是默认的。但是,它仍然有效不论,它只是增加了更多的复杂性。

Edit As pointed out in the comments, this is unnecessary if the Service and the client are running in the same process. Unless you specify otherwise, this is the default. However, it still works regardless, it just adds a bit more complexity.