Android: Passing a Service a Handler

后端 未结 2 1365
栀梦
栀梦 2020-12-11 08:40

So, I\'ve read the android AIDL documentation and have a general idea of how RPC works between an Activity and a Service. However, for my application it seems overboard to i

相关标签:
2条回答
  • 2020-12-11 08:48

    Android documentation suggests to work with a messenger as client interface in their Remote Messenger Service Sample: Remote Messenger Service Sample

    Code example can be found in the link above, no need to repost here I guess...

    Regards, Michael

    0 讨论(0)
  • 2020-12-11 09:06

    If your Service and Activity are in the same process, you can pass a Binder from your Service without doing the complicated RPC stuff:

    public class MyEasyButNotGoodPracticesBinder {
        public void gimmeHandler(Handler handler) {
            // you got it!
        }
    }
    
    IBinder mBinder = new MyEasyButNotGoodPracticesBinder();
    
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
    

    Then in your Activity when you get the IBinder object just cast it to a MyEasyButNotGoodPracticesBinder and call the gimmeHandler(Handler) method. Now, I think this is bad practices because if you ever want to put your Service in a separate process so that it doesn't crash the whole process if it crashes, this would break. I don't think it's that future-proof either. But it does work.

    An AIDL interface is not that hard - you may just want to do that instead.

    0 讨论(0)
提交回复
热议问题