带有aidl的bindService返回false

时间:2012-07-28 04:14:23

标签: android android-service aidl

我想提供一个可以被其他应用调用的服务。因此,我有一个服务和援助。但是当我尝试使用单独的应用程序绑定此服务(bindService)时,它只返回false,这意味着失败。这是我的代码。

PS:context已经是通过调用getApplicationContext()

获得的ApplicationContext

尝试绑定服务的代码

  private static ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            sService = XXXService.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            sService = null;
        }
    };

    private static synchronized XXXService getService(final Context context) {
        if (sService != null) {
            return sService;
        } else {
            intent.setClassName(context.getPackageName(), "com.xxx.someservice");
            if (context.bindService(intent, connection, Context.BIND_AUTO_CREATE)) {
                Log.i(TAG, "can bind");
            } else {
                Log.i(TAG, "can not bind");
            }
            return sService;
        }
    }

AndroidManifest

    <service android:name="com.xxx.someservice"
        android:process=":main"
        android:exported="true"/>

2 个答案:

答案 0 :(得分:1)

这似乎基本上是正确的。我认为问题是intent.setClassName(context.getPackageName(),“com.xxx.someservice”);应该是intent.setClassName(“Your.package.name.with.the.service”,“com.xxx.someservice”); 。 context.getPackageName()返回当前包名,因此如果您尝试在自己的包中绑定,这将起作用,但是您的问题使您看起来像是在单独的包中进行绑定。

答案 1 :(得分:1)

使用服务的操作名称为我工作。

E.g:

<service
    android:name="..."
    android:process="..." >
    <intent-filter>
        <action android:name="your-unique-action-name" />
    </intent-filter>
</service>

...
bindService(new Intent("your-unique-action-name"), mServiceConnection, BIND_AUTO_CREATE);