1

我想提供一个可以被其他应用程序调用的服务。因此,我有服务和助手。但是当我尝试使用单独的应用程序来绑定此服务(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"/>
4

2 回答 2

1

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

于 2012-07-28T04:29:50.057 回答
1

为服务使用操作名称对我有用。

例如:

<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);
于 2012-07-28T04:47:33.030 回答