Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

java - Android: Passing a Service a Handler

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 implement such features: basically, I want to pass a Service a nice handler so its thread can pass data to my Activity. Currently I'm getting around this by using a static public member (a hack) but I would prefer just passing a Handler object in the Service's starting Intent. E.g. I can easily pass ints to my service upon creation:

int x = 0;
Intent svc = new Intent(this, MyService.class);
svc.putExtra("x",x);
startService(svc);

However since a Handler isn't serialize-able , I haven't found a way to pass it to the service without a simple static member hack. Any insight? Or, am I just going to have to suck it up and do a formal RPC to the service?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...