【问题标题】:How a client process (in android IPC with aidl) be aware of remote sever class?客户端进程(在带有aidl的android IPC中)如何知道远程服务器类?
【发布时间】:2019-04-15 09:16:06
【问题描述】:

在 Android 官方 Aidl 文档中,IPC 客户端示例以“RemoteService.class”为目标明确声明了一个意图。但是,当服务器和客户端不在同一个包中时,如果没有设置依赖项,客户端不应该知道什么是“RemoteService”。这个例子是如何工作的?

参考:https://developer.android.com/guide/components/aidl.html

我搜索了几个工作示例,意图是使用 Action 而不是远程服务类对象设置的。

在 Android 文档中,

Intent intent = new Intent(Binding.this, RemoteService.class);
intent.setAction(IRemoteService.class.getName());
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

目前,我希望这应该修改为:

Intent intent = new Intent("<remote-service-intent-filter-in-androidmanifest>");
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

【问题讨论】:

    标签: java android ipc aidl


    【解决方案1】:

    您走在正确的道路上,但是如果您在清单中添加意图操作,那么您还应该在绑定服务时提及包名称。

    intent.setPackage("<remote service package name>");
    

    注意:为确保您的应用安全,请始终使用显式 启动服务时的意图并且不声明意图过滤器 您的服务。使用隐式意图启动服务是一种 安全隐患,因为您无法确定提供的服务 响应意图,用户看不到哪个服务启动。 从 Android 5.0(API 级别 21)开始,系统会抛出 如果您以隐式意图调用 bindService() 则异常。 https://developer.android.com/guide/components/services

    片段: 以下是我使用 setClassName API 连接到不同应用程序上的远程服务的方法。

    注意:这种方法不需要清单文件中的意图操作。

    在客户活动中。

    /**
     * Init Service
     */
    private void initService() {
        if (mSampleService == null) {
            Intent i = new Intent();
    
            // set intent action
            i.setAction("com.hardian.sample.aidl.ISampleService");
            // mention package name with service's canaonical name
            i.setClassName("com.hardian.sample", "com.hardian.sample.aidl.SampleAidlService");
    
            // binding to a remote service
            bindService(i, mSampleServiceConnection, Service.BIND_AUTO_CREATE);
        } 
    }
    

    服务中

     /**
     * {@inheritDoc}
     */
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind called");
        if (ISampleService.class.getName().equals(intent.getAction())) {
            return mSampleServiceBinder;
        }
        return null;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-01
      相关资源
      最近更新 更多