Android IPC,服务未获得实例化

时间:2015-03-18 17:04:44

标签: android android-service ipc aidl

我有一个服务,它位于像这样的lib项目中

public abstract class MyService extends Service{
    //service body here 
}

我将我的aidl文件设置为与远程服务进行通信,该服务也包含在复制aidl文件的lib项目中

package mypackage;

// Declare the communication interface which holds all of our exposed functions.
interface IMyService {
    //interface body here 
}

在lib清单中,我已经声明了这个服务

<service
    android:name="mypackage.core.MyService"
    android:enabled="true"
    android:exported="true"
    android:process=":remote" >

    <intent-filter>
        <action android:name="mypackage.IMyService" />
    </intent-filter>

</service>

我已将此lib包含在我的应用程序中,但当我尝试从应用程序绑定服务时,它未实例化。任何人都可以告诉我我做错了什么,如果是这样,我可以指出一条出路。服务in在另一个属于lib的类中开始,如此

try{
    Intent i = new Intent(MyService.class.getName());
    i.setPackage("mypackage");
    // start the service explicitly.
    // otherwise it will only run while the IPC connection is up.       
    mAppContext.startService(i);
    boolean ret = mAppContext.bindService(i,
            mConnection, Service.BIND_AUTO_CREATE);
    if(!ret){
        MyLogger.log("Error");
    }
}catch(Exception e){
    MyLogger.log("err");
}

服务绑定API始终返回false,这将是什么问题。这是创建RemoteService的重要方式吗?我是否需要在应用清单中添加此服务,如果是这样的话?

1 个答案:

答案 0 :(得分:6)

  

会出现什么问题

首先,您的Intent与您的<service>不匹配。

Intent i = new Intent(MyService.class.getName());

您传递的动作String看起来像mypackage.core.MyService。但是,这不是<action>的{​​{1}}:

Service

因此,您的<action android:name="mypackage.IMyService" /> 与任何内容都不匹配,您无法绑定。


其次,您的Intent 非常不安全。任何想要绑定它的应用程序。如果您希望其他应用程序绑定到它,那很好,但通过一些权限保护它,以便用户对哪些应用程序可以绑定它进行投票。


第三,您使用隐式Service进行绑定,该隐式Intent使用类似操作字符串的内容。这不适用于Android 5.0+,因为您无法再使用隐式Intent绑定到服务。使用隐式Intent来发现服务很好,但是您需要将Intent转换为包含组件名称的显式服务。以下是我在this sample app中执行此操作的方法:

  @Override
  public void onAttach(Activity host) {
    super.onAttach(host);

    appContext=(Application)host.getApplicationContext();

    Intent implicit=new Intent(IDownload.class.getName());
    List<ResolveInfo> matches=host.getPackageManager()
                                  .queryIntentServices(implicit, 0);

    if (matches.size()==0) {
      Toast.makeText(host, "Cannot find a matching service!",
                      Toast.LENGTH_LONG).show();
    }
    else if (matches.size()>1) {
      Toast.makeText(host, "Found multiple matching services!",
                      Toast.LENGTH_LONG).show();
    }
    else {
      Intent explicit=new Intent(implicit);
      ServiceInfo svcInfo=matches.get(0).serviceInfo;
      ComponentName cn=new ComponentName(svcInfo.applicationInfo.packageName,
                                         svcInfo.name);

      explicit.setComponent(cn);
      appContext.bindService(explicit, this, Context.BIND_AUTO_CREATE);
    }
  }

  

这是创建RemoteService的重要方式吗?

很少有人创建远程服务。它们很难保护,很难处理协议中的版本更改等。在您的情况下,我不知道您认为自己需要远程服务的原因,因为您明确地绑定了自己应用程序中的服务。 / p>

相关问题