一簡(jiǎn)介
從android 10開始袋励,hwbinder引入了lazy service模式,android R正式引入到binder中沟于。使用lazy方式注冊(cè)的binder或者h(yuǎn)idl servicer在client退出后確認(rèn)相關(guān)service沒有client調(diào)用后會(huì)自動(dòng)退出,讓出系統(tǒng)資源,節(jié)省內(nèi)存占用日戈。比較智能。
二 原理
1) hidl service lazy 注冊(cè)接口
class LazyServiceRegistrarImpl {
public:
LazyServiceRegistrarImpl() : mClientCallback(new ClientCounterCallback) {}
status_t registerService(const sp<::android::hidl::base::V1_0::IBase>& service,
const std::string& name);
private:
sp<ClientCounterCallback> mClientCallback;
};
注冊(cè)hidl service成功后多了個(gè)onClients回調(diào)孙乖,在client連接數(shù)為0時(shí)退出service
/**
* onClients is oneway, so no need to worry about multi-threading. Note that this means multiple
* invocations could occur on different threads however.
*/
Return<void> ClientCounterCallback::onClients(const sp<::android::hidl::base::V1_0::IBase>& service,
bool clients) {
if (clients) {
mNumConnectedServices++;
} else {
mNumConnectedServices--;
}
LOG(INFO) << "Process has " << mNumConnectedServices << " (of " << mRegisteredServices.size()
<< " available) client(s) in use after notification " << getDescriptor(service.get())
<< " has clients: " << clients;
if (mNumConnectedServices == 0) {
tryShutdown();
}
return Status::ok();
}
在hwservicemanager側(cè)注冊(cè)的Hidl service會(huì)判斷當(dāng)前的client數(shù)浙炼,如果有client那么就發(fā)送sendClientCallbackNotifications(true);通知對(duì)應(yīng)的hidl service。如果client為空的話sendClientCallbackNotifications(false)通知hidl service client為空了唯袄。
ssize_t HidlService::forceHandleClientCallbacks(bool isCalledOnInterval) {
ssize_t count = getNodeStrongRefCount();
// binder driver doesn't support this feature
if (count == -1) return count;
bool hasClients = count > 1; // this process holds a strong count
if (mGuaranteeClient) {
// we have no record of this client
if (!mHasClients && !hasClients) {
sendClientCallbackNotifications(true);
}
// guarantee is temporary
mGuaranteeClient = false;
}
if (hasClients && !mHasClients) {
// client was retrieved in some other way
sendClientCallbackNotifications(true);
}
// there are no more clients, but the callback has not been called yet
if (!hasClients && mHasClients && isCalledOnInterval) {
mNoClientsCounter++;
if (mNoClientsCounter >= kNoClientRepeatLimit) {
sendClientCallbackNotifications(false);
}
}
return count;
}
forceHandleClientCallbacks調(diào)用的幾個(gè)時(shí)機(jī):
1) 在client get service時(shí)通知hidl servie mNumConnectedServices++
- 取消注冊(cè)時(shí)tryUnregister
3) ClientCallbackCallback 調(diào)用mManager->handleClientCallbacks();interval是5秒鐘
三 總結(jié)
從android R開始弯屈,binder借鑒了hidl也引入了lazy模式,具體見frameworks/native/libs/binder/LazyServiceRegistrar.cpp恋拷,原理同HIDL方式