安卓:传递一个服务处理程序 [英] Android: Passing a Service a Handler

查看:132
本文介绍了安卓:传递一个服务处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我读过了Android AIDL 的文档,并有的RPC的活动和服务之间是如何工作的总体思路。但是,我的应用程序似乎过分实现这样的特点:基本上,我想通过一个服务一个很好的处理程序,以便它的线程可以将数据传递到我的活动。目前,我得到解决此通过使用静态公共成员(黑客),但我会preFER刚好路过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);

然而,由于处理程序不序列化,能,我还没有找到一种方法,将它传递给服务,而不简单的静态成员破解。任何见解?或者,我只是将不得不吮吸它,做一个正式的RPC服务?

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?

推荐答案

如果你的服务和活动都在同一过程中,你可以从你的服务传递一个活页夹,而不做复杂的RPC的东西:

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;
}

然后在你的活动时,你得到的IBinder对象,只是将其转换为一个 MyEasyButNotGoodPracticesBinder 并调用 gimmeHandler(处理器)方法。现在,我觉得这是不好的做法,因为如果你曾经想要把你的服务在一个单独的进程,这样,如果它崩溃不崩溃的全过程,这将打破。我不认为这是面向未来的两种。但它确实工作。

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.

这是AIDL接口并不难 - 你可能只是想这样做,而不是

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

这篇关于安卓:传递一个服务处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆