开发者

Best way for Service that starts Activity to communicate with it

I have a service that listens to a socket. When receiving certain input it is to create an activity. When receiving other input, it开发者_JAVA百科 is to kill this activity. I have struggled for a while to make the service communicate with the activity through AIDL (http://developer.android.com/guide/developing/tools/aidl.html), but this seems to not be effective. I think AIDL is only effective when the process that is to be talked to is a service, not when it is an activity? I would love some directions or suggestions on how to solve my problem.

Cheers,


I have a service that listens to a socket. When receiving certain input it is to create an activity.

Please make this configurable. Services should not be starting activities except in very unusual circumstances (e.g., the socket is a SIP connection and you are creating a VOIP client). Popping up an activity interrupts the user in whatever they are doing.

When receiving other input, it is to kill this activity.

The only scenario I have seen where this is a valid pattern is dismissing the in-call screen when the other party hangs up the line. If you are creating a VOIP client, your proposed pattern should be OK, but otherwise, please reconsider having the activity vanish in the middle of the user using it.

I think AIDL is only effective when the process that is to be talked to is a service, not when it is an activity?

No, it works in the reverse direction too, but usually only if the activity is the one starting the service and binding to it. More importantly, AIDL is only for cross-process communication.

I would love some directions or suggestions on how to solve my problem.

You have not really provided enough information on the nature of the communication to give you a thorough answer. What, exactly, is the service trying to tell the activity? Is the activity also trying to communicate with the service?

The recommended pattern for ongoing communication from an activity to a service is to use the local binding pattern. You will find an example of this in your SDK samples, and you can find one here as well.

The service then has options for communicating back to the client: via a callback (e.g., the Handler in the answer supplied by Mr. Smiljanić) or via broadcast Intents. In the case of the callback, the activity would need to bind to the service in order to get access to an API to provide the callback object. The service would then hold onto that object and call methods on it during key events.

If your service is doing its primary work on a background thread, you will need to ensure that your UI operations get performed on the UI thread. The Handler is one approach to that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜