service binder将自定义的aidl回调接口作为null接收

时间:2014-12-11 17:38:53

标签: android service callback aidl

我在绑定服务中传递自定义AIDL回调接口。服务绑定器将其接收为空。

服务和客户端在不同的进程中运行。用于绑定服务和回调存根适配器aidl和类的请求,响应,服务,绑定器,实用程序类位于android库项目中,服务和客户端类(在单独的应用程序中)都使用它。

以下是相关代码(减去导入)。 (编译正常,没有运行时异常)

// service callback IResponseReceiver.aidl
oneway interface IResponseReceiver {
    void onReceiveResponseA(in int statusCode, in ResponseA response);
    void onReceiveResponseB(in int statusCode, in ResponseB response);
}

// service aidl
oneway interface IService {
    void executeA(in RequestA request, in IResponseReceiver receiver);
    void executeB(in RequestB request, in IResponseReceiver receiver);
}

// service binder
public class ServiceImpl extends IService.Stub {
    private ExecutorService mExecutor;

    @Override
    public void executeA(RequestA request, IResponseReceiver receiver) throws RemoteException {
        mExecutor.execute(handle(request, receiver)); // receiver == null here
    }

    @Override
    public void executeB(RequestB request, IResponseReceiver receiver) throws RemoteException {
        mExecutor.execute(handle(request, receiver)); // receiver == null here
    }
}

// service callback adapter class
class ResponseReceiver extends IResponseReceiver.Stub {
    @Override
    public void onReceiveResponseA(int statusCode, ResponseA response)
        throws RemoteException {
    }

    @Override
    public void onReceiveResponseB(int statusCode, ResponseB response)
        throws RemoteException {
    }
}

// service callback class in client
class ClientResponseReceiver extends ResponseReceiver {
    @Override
    public void onReceiveResponseB(int statusCode, ResponseB response)
        throws RemoteException {
        // do something
        }
}

// utility class for calling bound service method
class ServiceChannel implements ServiceConnection {
    private IService mService;

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mService = IService.Stub.asInterface(service);
    }

    void execute(RequestA request, ResponseReceiver receiver) {
        mService.executeA(request, receiver); // receiver != null here
    }
}

调用startService()的活动也会调用客户端应用程序的startActivity(FLAG_ACTIVITY_NEW_TASK)。客户端应用程序绑定服务并调用IService.executeA()。

我做错了什么?没有堆栈跟踪显示任何错误。

提前致谢。

3 个答案:

答案 0 :(得分:0)

咄。抱歉这花了很长时间。

AIDL为IService中的方法定义只接受一个参数。第二个论点是没有通过Binder。你需要:

interface IService {
    void executeA(in RequestA request, in IResponseReceiver receiver);
    void executeB(in RequestB request, in IResponseReceiver receiver);
}

答案 1 :(得分:0)

该服务从App-1启动。 App-1还使用FLAG_ACTIVITY_NEW_TASK启动App-2。 App-2尝试绑定到服务。

看起来好像是FLAG_ACTIVITY_NEW_TASK。

答案 2 :(得分:0)

在android AIDL中,你不能使用普通的java对象作为回调或接收器,因为它们处于不同的进程中。 考虑使用RemoteCallbackList;