Android remote service callbacks

后端 未结 1 1876
长情又很酷
长情又很酷 2020-12-05 12:18

(I have a remote service with an AIDL interface that is used by several client apps. I would like to add an asynchronous method to the interface for calls t

相关标签:
1条回答
  • 2020-12-05 12:42

    A callback method/listener is the right thing to do. (As CommonsWare says, it's pretty much the same thing). I would say it's much simpler than fiddling around with BroadcastReceivers, since you're already using aidl.

    Something like this:

    IAsyncThing.aidl:

    package com.my.thingy;
    
    import com.my.thingy.IAsyncThingListener;
    
    interface IAsyncThing {
      void doSomething(IAsyncThingListener listener);
    }
    

    IAsyncThingListener.aidl:

    package com.my.thingy;
    
    import com.my.thingy.IAsyncThingListener;
    
    interface IAsyncThingListener {
      void onAsyncThingDone(int resultCodeIfYouLike);
    }
    

    You can enforce that only your apps can bind to the service by using a signature-level permission on your service (see the note on 'service permissions' here: http://developer.android.com/guide/topics/security/permissions.html). Specifically:

    • Declare a permission in your service's AndroidManifest.xml. Ensure it is signature level.
    • Add that permission in your service tag
    • In all the other apps, use uses-permission to use it.

    A couple of other things to bear in mind:

    • In the caller, you'll need to subclass IAsyncThingListener.Stub. Your calling application code may already be subclassing something else, so that means you'd have to use an extra (probably inner) class to receive the completion notification. I mention this only because this might be the answer to question #2 - which I don't fully understand.
    • If the service is potentially in different processes from the caller, each should register for death notification of the other using IBinder.linkToDeath.
    0 讨论(0)
提交回复
热议问题