代码之家  ›  专栏  ›  技术社区  ›  Donal Rafferty

Android正在获取与活动通信的服务?

  •  2
  • Donal Rafferty  · 技术社区  · 15 年前

    我目前在我的应用程序中有一个服务和一个活动。

    I currently bind the Service to the activity without using AIDL as the Service and the Activity are in the same application.

    这允许我在需要时从活动中的服务调用方法,但不允许我在需要时从服务中调用活动的方法。

    有人能评论一下什么是实现这一目标的最佳方法吗?

    我可以使用意图,但有其他选择吗?

    我希望在服务和活动之间有紧密的通信,我希望能够在事件发生时从我的服务调用活动方法。

    感谢Ognian的建议。

    编辑2:

    I now have it working the way I want, however I have come across a problem.

    My service gets status updates and my Activity is then supposed to react to the update sent on from the Service.

    The problem is that when I start my activity I get the Dialling Status and then Connected status before the onBind is called and I get the instance of iCallDialogActivity.

    logcat的以下输出可能会使事情更清楚。

    06-28 10:56:48.702: DEBUG/TestPhone(3498): Status: EStatusDialling
    06-28 10:56:48.751: DEBUG/TestPhone(3498): Status: EStatusConnected
    06-28 10:56:49.122: DEBUG/TestPhone(3498): Status: onBind Called    <------------- 
    06-28 10:56:49.141: DEBUG/TestPhone(3498): Status: iCallDialogActivity instance  <------------- 
    06-28 10:56:51.641: DEBUG/TestPhone(3498): Status: EStatusDisconnecting
    06-28 10:56:51.651: DEBUG/TestPhone(3498): Status: EStatusIdle
    

    I need to be able to use my iCallDialogActivity when I get the Dialling and Connected Status notifications.

    But this gives me a NullPointer Exception due to it not being created in time when my Activity starts, binding is the first thing I do in my Activities onCreate().

    有什么方法可以让它直接绑定吗?

    1 回复  |  直到 15 年前
        1
  •  3
  •   ognian    15 年前

    You can't call directly methods on your Activity's instance, you must use the same IPC mechanism you're calling Service methods trough AIDL.

    First, you need to declare some methods you wish to expose as callbacks. Do that in a separate .aidl file. Then add a setter for that callback to the Service's AIDL, for example:

    void setMyCallback(inout IMyCallback myCallback);
    

    如果你做了imycallback.aidl.记住 import 它在service.aidl中,即使它在同一个包中。在活动中,从该.aidl实例化一个存根,并在回调之前将其传递给服务。