我在模块 A 中实现了一个服务。现在应用程序 B 和 C 使用这个库来绑定(bind)服务,使用 bindService(service, connection, BIND_AUTO_CREATE)
但它总是创建一个新的服务实例。我正在使用 Messenger
将活页夹返回到连接对象。如果我使用AIDL,如何实现共享同一个服务实例?我已经阅读并尝试了几乎所有与此问题相关的 stackoverflow 答案。但是我仍然无法实现我上面解释的内容。
此服务的 list 在模块 A 中定义,进程属性的完整进程名称和导出的启用设置为 true。
<service
android:name="io.packagename.LocationService"
android:enabled="true"
android:exported="true"
android:permission="android.permission.ACCESS_FINE_LOCATION"
android:process="io.packagename.locationService" />
位置服务类:
class LocationService extends Service {
IncomingHandler handler = new IncomingHandler()
Messenger messenger = new Messenger(handler)
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind")
return messenger.binder
}
}
任何帮助深表感谢。
最佳答案
引用 docs :
As discussed in the Services document, you can create a service that is both started and bound. That is, the service can be started by calling startService(), which allows the service to run indefinitely, and also allow a client to bind to the service by calling bindService().
一个例子:
For example, a music player might find it useful to allow its service to run indefinitely and also provide binding. This way, an activity can start the service to play some music and the music continues to play even if the user leaves the application. Then, when the user returns to the application, the activity can bind to the service to regain control of playback.
我相信这适用于您的情况,因此您可以根据需要启动服务并将客户端绑定(bind)到它。
关于Android 与跨多个应用的现有服务绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38827203/