我有一个包含三个模块的项目:
com.example.library - 定义 AIDL 接口(interface)
// IRemoteService.aidl
package com.example.library;
interface IRemoteService {
int add(int a,int b);
int sub(int a,int b);
}
com.example.server - 实现服务,取决于库
// AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest ...
package="com.example.server">
<application
...>
<service android:name=".RemoteService"/>
</application>
</manifest>
// RemoteService.kt
class RemoteService: Service() {
override fun onBind(p0: Intent?): IBinder {
return object : IRemoteService.Stub() {
@Throws(RemoteException::class)
override fun add(a: Int, b: Int): Int {
return a + b
}
@Throws(RemoteException::class)
override fun sub(a: Int, b: Int): Int {
return a - b
}
}
}
}
com.example.client - 使用服务,取决于库
// MainActivity.kt
class MainActivity : AppCompatActivity(), ServiceConnection {
companion object {
const val TAG = "MainActivity"
}
private var service: IRemoteService? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.button).setOnClickListener {
service?.let {
Log.i(TAG, it.add(10, 20).toString())
}
}
}
override fun onServiceConnected(componentName: ComponentName?, binder: IBinder?) {
Log.i(TAG, "onServiceConnected")
service = IRemoteService.Stub.asInterface(binder)
}
override fun onServiceDisconnected(componentName: ComponentName?) {
Log.i(TAG, "onServiceDisconnected")
service = null
}
override fun onStart() {
super.onStart()
bindService(Intent("com.example.server.RemoteService")
.setPackage("com.example.server"), this, BIND_AUTO_CREATE)
}
override fun onStop() {
unbindService(this)
super.onStop()
}
}
问题是 onServiceConnected
永远不会被触发,这意味着服务永远不会启动。
请问有什么想法可能是什么原因吗?
最佳答案
bindService()
Android 11+ 受 package visibility rules 管辖。您的服务应用程序不需要更改,但客户端应用程序需要更改 - 将调用 bindService()
的代码— will need a <queries>
element in its manifest ,标识具有服务的应用程序的应用程序 ID。
<queries>
<package android:name="com.example.server" />
</queries>
关于android - bindService 无法使用 BIND_AUTO_CREATE 启动服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72862484/