如何将一个服务绑定到多个应用程序?

3
我们在Android编程中的服务方面非常新手。我们已经成功地使一个应用程序运行了一个服务。现在,我们有一个所有者应用程序“AppA”,它启动了该服务,还有另一个应用程序“AppB”想要使用该服务。那么,我们如何将其绑定到同一运行服务的应用程序“AppB”?是否应该创建多个服务实例(这是可能的吗?)或者我们可以将多个应用程序绑定到服务的同一实例上?
我们创建了一个名为initservice()的函数,以便将活动绑定到服务。
所有者应用程序A在initService()中的代码:
connection = new SampleServiceConnection();
Intent i = new Intent();
i.setClassName("com.example.basicstuff",com.example.basicstuff.SampleService.class.getName());
this.startService(i);
boolean ret = bindService(i, connection, Context.BIND_AUTO_CREATE);
Log.d(TAG, "initService() bound with " + ret);

SampleServiceConnection类是实现Andorid的ServiceConnection类的类。我已经实现了onServiceConnected()和onServiceDisconnected()函数。我的第一个应用程序“AppA”的包名为com.example.basicstuff,扩展Service类的类是SampleService。在执行bindService()函数后,LogCat显示“initService()绑定成功”。

我还创建了一个名为ISampleService的.aidl文件。

App B的代码在initService()中。

connection = new SampleServiceConnection();
Intent i = new Intent("com.example.GameBook_Chat.ISampleService");
System.out.println(this.startService(i));
System.out.println("service running");
boolean ret = bindService(i, connection, Context.BIND_AUTO_CREATE);
Log.d(TAG, "initService() bound with " + ret);

我的第二个包名是com.example.GameBook_Chat,它想要与上述代码中运行的相同服务进行通信。在执行bindService()函数时,LogCat服务显示“initService()绑定失败”。

基本上,我无法使第二个应用程序与服务通信。有人能告诉我可以做哪些更正吗?

1个回答

0
每次调用`bindService()`都会导致调用服务的`onBind()`方法。服务可以自由地向每个客户端返回相同的实现`IBinder`接口的对象。你可以使用像`checkCallingPermission()`这样的方法来验证任何调用,或者如果你只想知道调用者是谁,你可以使用`getCallingUid()`。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接