startActivityForResult的服务模拟startActivityForResult

2023-09-06 00:35:10 作者:情深已故

尽管similar有人问,我目前存在的情况: 我的应用程序包括主要背景服务。我要开始对外活动,并获得返回的结果。

Despite similar question was asked, I have differnet situation: My app consists mostly of a background Service. I want to start external activities and get results back.

我看到几个选项:

创建虚拟活动并保持对它的引用,使用它的 startActivityForResult 。这会消耗相当多的内存,因为我们知道。

Create dummy Activity and keep reference to it for using its startActivityForResult. This consumes quite a lot of memory, as we know.

使用广播意图,而不是Android的业绩基础:要求客户端活动关闭之前播出他们的结果。这种突破的想法,并没有那么性能效率。

Use Broadcast Intents instead of Android's results infrastructure: ask client activities to broadcast their results before closing. This kind of breaks the idea and not so performance-efficient.

使用仪表直接 - 尝试从startActivityForResult复制code到我的服务。

Use Instrumentation directly - try to copy code from startActivityForResult into my Service.

使用服务接口 - 序列,并添加 AIDL 连接到意向启动的活动。在这种情况下的活动应电话服务直接的提供的结果,而不是。

Use Service interfaces - serialize and add AIDL connection to the Intent for starting an Activity. In this case Activity should call Service directly instead of providing result.

第三种方式感觉更接近到Android我,但我不知道是否有可能做的事情 - 服务不具有其仪表以及默认的实现似乎总是返回null。

The third approach feels closer to Android for me, but I'm not sure if it's possible to do - Service does not have its Instrumentation, and default implementation seems to always return null.

也许你有任何其他想法?

Maybe you have any other ideas?

推荐答案

我觉得选项2是在Android上最惯用的方式。使用 startActivityForResult 活动是一个同步/阻塞调用,即父活动等待,并没有做任何事情,直到孩子完成。当从服务工作和活动进行交互的主要做异步/非阻塞调用,即服务​​调用出来做一些工作,然后等待一个信号告诉它,它可以继续下去。

I think option 2 is the most idiomatic way on android. Using startActivityForResult from an Activity is a synchronous/blocking call, i.e., the parent activity waits and does not do anything until the child is done. When working from a Service and interacting with activities your primarily doing asynchronous/non-blocking calls, i.e., the service calls out for some work to be done and then waits for a signal to tell it that it can continue.

如果您使用的是的Andr​​oid本地服务模式的话你可以有你的活动获得服务的参考,然后调用特定的功能后,已完成其工作。尝试你的选项3会适得其反什么框架提供给你。

If you are using the android local service pattern then you can have your activities acquire a reference of the Service and then call a specific function after it has performed its work. Attempting your option 3 would be counter to what the framework provides for you.

 
精彩推荐
图片推荐