Table of Contents
class ContextHubService extends IContextHubService.Stub(is a)
class ContextHubService 包含的类成员(has a)
getContextHubProxy获得IContextHub的代理
每个contextHub: registerClient到 contextHubService
每个ContextHub向ContextHub调用registerCallback
有关ContextHub的IContextHubService接口
NanoAppcreate/Enable/Disable/Load/Unload/Query:Transcation
IContextHubClient: sendMessageToNanoApp
system service: contexthub
contexthub service的实现代码:frameworks/base/services/core/java/com/android/server/location/ContextHubService.java
class ContextHubService类的结构
class ContextHubService extends IContextHubService.Stub(is a)
实现由IContextHubService.aidl生成的IContextHubService.java中的server类: IContextHubService.Stub
class ContextHubService 包含的类成员(has a)
private final Context mContext;
private final Map<Integer, ContextHubInfo> mContextHubIdToInfoMap;
private final List<ContextHubInfo> mContextHubInfoList;
// Proxy object to communicate with the Context Hub HAL
private final IContexthub mContextHubProxy;
// The manager for transaction queue
private final ContextHubTransactionManager mTransactionManager;
// The manager for sending messages to/from clients
private final ContextHubClientManager mClientManager;
// The manager for the internal nanoapp state cache
private final NanoAppStateManager mNanoAppStateManager = new NanoAppStateManager();
内部类 ContextHubServiceCallback
注册到 HAL:ContextHub的函数,当时间发生时被调用,这些函数的实现会把数据从ContextHub传到ContextHubService 并同过client注册的回调函数:IContextHubClientCallback 和 IContextHubTransactionCallback传到client
private class ContextHubServiceCallback extends IContexthubCallback.Stub {
private final int mContextHubId;
//构造函数引入mContextHubId,具体的实现函数也add参数:contextHubId,
//成员函数调用ContextHubService的成员变量对象mClientManager、ContextHubTransactionManager
//进而对象的成员函数,而这些成员函数又调用其他类如ContextHubClientBroker
ContextHubServiceCallback(int contextHubId) {
mContextHubId = contextHubId;
}
@Override
public void handleClientMsg(ContextHubMsg message) {
handleClientMessageCallback(mContextHubId, message);
}
@Override
public void handleTxnResult(int transactionId, int result) {
handleTransactionResultCallback(mContextHubId, transactionId, result);
}
@Override
public void handleHubEvent(int eventType) {
handleHubEventCallback(mContextHubId, eventType);
}
@Override
public void handleAppAbort(long nanoAppId, int abortCode) {
handleAppAbortCallback(mContextHubId, nanoAppId, abortCode);
}
@Override
public void handleAppsInfo(ArrayList<HubAppInfo> nanoAppInfoList) {
handleQueryAppsCallback(mContextHubId, nanoAppInfoList);
}
}
构造函数ContextHubService
public ContextHubService(Context context) {
mContext = context;
//1.
mContextHubProxy = getContextHubProxy();
//2.
mClientManager = new ContextHubClientManager(mContext, mContextHubProxy);
//3.
mTransactionManager = new ContextHubTransactionManager(
mContextHubProxy, mClientManager, mNanoAppStateManager);
//4.
List<ContextHub> hubList;
hubList = mContextHubProxy.getHubs();
mContextHubIdToInfoMap = Collections.unmodifiableMap(
ContextHubServiceUtil.createContextHubInfoMap(hubList));
mContextHubInfoList = new ArrayList<>(mContextHubIdToInfoMap.values());
//5.
HashMap<Integer, IContextHubClient> defaultClientMap = new HashMap<>();
for (int contextHubId : mContextHubIdToInfoMap.keySet()) {
IContextHubClient client = mClientManager.registerClient(//5.1
createDefaultClientCallback(contextHubId), contextHubId);
defaultClientMap.put(contextHubId, client);
mContextHubProxy.registerCallback(//5.2
contextHubId, new ContextHubServiceCallback(contextHubId));
queryNanoAppsInternal(contextHubId);
}
mDefaultClientMap = Collections.unmodifiableMap(defaultClientMap);
}
getContextHubProxy获得IContextHub的代理
IContextHub.hal生成的文件
out/soong/.intermediates/hardware/interfaces/contexthub/1.0/android.hardware.contexthub-V1.0-java_gen_java/gen/android/hardware/contexthub/V1_0/IContexthub.java
import android.hardware.contexthub.V1_0.IContexthub;
public interface IContexthub extends android.hidl.base.V1_0.IBase {
public static final String kInterfaceName = "android.hardware.contexthub@1.0::IContexthub";
public static IContexthub getService(String serviceName, boolean retry) throws android.os.RemoteException {
return IContexthub.asInterface(android.os.HwBinder.getService("android.hardware.contexthub@1.0::IContexthub", serviceName, retry));
public static IContexthub getService(boolean retry) throws android.os.RemoteException {
return getService("default", retry);
}
public static final class Proxy implements IContexthub {
private android.os.IHwBinder mRemote;
}
public static abstract class Stub extends android.os.HwBinder implements IContexthub {
@Override
public android.os.IHwBinder asBinder() {
return this;//就是实现接口的class
}
}
}
List<ContextHub> hubList;
hubList = mContextHubProxy.getHubs();
HashMap<Integer, IContextHubClient> defaultClientMap = new HashMap<>();
for (int contextHubId : mContextHubIdToInfoMap.keySet()) {
IContextHubClient client = mClientManager.registerClient(
createDefaultClientCallback(contextHubId), contextHubId);
defaultClientMap.put(contextHubId, client);
mContextHubProxy.registerCallback(
contextHubId, new ContextHubServiceCallback(contextHubId));
queryNanoAppsInternal(contextHubId);
}
mDefaultClientMap = Collections.unmodifiableMap(defaultClientMap);
每个contextHub: registerClient到 contextHubService
(使用由createDefaultClientCallback生成的DefaultClientCallback, 这里没有使用clinet传入的方式)
/**
* Registers a new client with the service.
*
* @param clientCallback the callback interface of the client to register
* @param contextHubId the ID of the hub this client is attached to
*
* @return the client interface
*
*/
IContextHubClient registerClient(
IContextHubClientCallback clientCallback, int contextHubId) {
ContextHubClientBroker broker = createNewClientBroker(clientCallback, contextHubId);
return IContextHubClient.Stub.asInterface(broker);
}
private synchronized ContextHubClientBroker createNewClientBroker(
IContextHubClientCallback clientCallback, int contextHubId) {
ContextHubClientBroker broker = null;
int id = mNextHostEndpointId;
for (int i = 0; i <= MAX_CLIENT_ID; i++) {
if (!mHostEndPointIdToClientMap.containsKey((short)id)) {
broker = new ContextHubClientBroker(
mContext, mContextHubProxy, this, contextHubId, (short)id, clientCallback);
mHostEndPointIdToClientMap.put((short)id, broker);
mNextHostEndpointId = (id == MAX_CLIENT_ID) ? 0 : id + 1;
break;
}
id = (id == MAX_CLIENT_ID) ? 0 : id + 1;
}
return broker;
}
ContextHubClientBroker(//引入参数 mHostEndPointId
Context context, IContexthub contextHubProxy, ContextHubClientManager clientManager,
int contextHubId, short hostEndPointId, IContextHubClientCallback callback) {
mContext = context;
mContextHubProxy = contextHubProxy;
mClientManager = clientManager;
mAttachedContextHubId = contextHubId;
mHostEndPointId = hostEndPointId;
mCallbackInterface = callback;
}
每个ContextHub向ContextHub调用registerCallback
mContextHubProxy.registerCallback( contextHubId, new ContextHubServiceCallback(contextHubId));
ContextHubServiceCallback就是上面说的内部类
有关ContextHub的IContextHubService接口
int[] getContextHubHandles();
ContextHubInfo getContextHubInfo(int contextHubHandle);
List<ContextHubInfo> getContextHubs();
这些函数的返回值都来自构造函数赋值的mContextHubIdToInfoMap。
contextHubHandle指的是mContextHubIdToInfoMap的key,
@Override
public int[] getContextHubHandles() throws RemoteException {
checkPermissions();
return ContextHubServiceUtil.createPrimitiveIntArray(mContextHubIdToInfoMap.keySet());
}
@Override
public ContextHubInfo getContextHubInfo(int contextHubHandle) throws RemoteException {
checkPermissions();
return mContextHubIdToInfoMap.get(contextHubHandle);//在构造函数时赋值
}
@Override
public List<ContextHubInfo> getContextHubs() throws RemoteException {
checkPermissions(); //mContextHubInfoList = new ArrayList<>(mContextHubIdToInfoMap.values());
return mContextHubInfoList;
}
ContextHubInfo
public class ContextHubInfo implements Parcelable {//成员变量
private int mId;
private String mName;
private String mVendor;
private String mToolchain;
private int mPlatformVersion;
private int mToolchainVersion;
private float mPeakMips;
private float mStoppedPowerDrawMw;
private float mSleepPowerDrawMw;
private float mPeakPowerDrawMw;
private int mMaxPacketLengthBytes;
private byte mChreApiMajorVersion;
private byte mChreApiMinorVersion;
private short mChrePatchVersion;
private long mChrePlatformId;
private int[] mSupportedSensors;
}
dump toString
@Override
public String toString() {
String retVal = "";
retVal += "ID/handle : " + mId;
retVal += ", Name : " + mName;
retVal += "\n\tVendor : " + mVendor;
retVal += ", Toolchain : " + mToolchain;
retVal += ", Toolchain version: 0x" + Integer.toHexString(mToolchainVersion);
retVal += "\n\tPlatformVersion : 0x" + Integer.toHexString(mPlatformVersion);
retVal += ", SwVersion : "
+ mChreApiMajorVersion + "." + mChreApiMinorVersion + "." + mChrePatchVersion;
retVal += ", CHRE platform ID: 0x" + Long.toHexString(mChrePlatformId);
retVal += "\n\tPeakMips : " + mPeakMips;
retVal += ", StoppedPowerDraw : " + mStoppedPowerDrawMw + " mW";
retVal += ", PeakPowerDraw : " + mPeakPowerDrawMw + " mW";
retVal += ", MaxPacketLength : " + mMaxPacketLengthBytes + " Bytes";
return retVal;
}
import java.io.PrintWriter;
/**
* Prints an object.
* @param obj The <code>Object</code> to be printed
* @see java.lang.Object#toString()
*/
public void print(Object obj) {
write(String.valueOf(obj));
}
@Override
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
pw.println("Dumping ContextHub Service");
pw.println("");
// dump ContextHubInfo
pw.println("=================== CONTEXT HUBS ====================");
for (ContextHubInfo hubInfo : mContextHubIdToInfoMap.values()) {
pw.println(hubInfo);//这里输出的就是上面的toString
}
}
有关NanoApp的接口
queryNanoApps
public void queryNanoApps(int contextHubId, IContextHubTransactionCallback transactionCallback)
throws RemoteException {
checkPermissions();
ContextHubServiceTransaction transaction = mTransactionManager.createQueryTransaction(
contextHubId, transactionCallback);
mTransactionManager.addTransaction(transaction);
}
ContextHubServiceTransaction createQueryTransaction(
int contextHubId, IContextHubTransactionCallback onCompleteCallback) {
return new ContextHubServiceTransaction(
mNextAvailableId.getAndIncrement(), ContextHubTransaction.TYPE_QUERY_NANOAPPS) {
@Override
/* package */ int onTransact() {
try {
return mContextHubProxy.queryApps(contextHubId);
}
}
@Override
/* package */ void onTransactionComplete(@ContextHubTransaction.Result int result) {
onQueryResponse(result, Collections.emptyList());
}
@Override
/* package */ void onQueryResponse(
@ContextHubTransaction.Result int result, List<NanoAppState> nanoAppStateList) {
try {//通过client注册的callback把结果返给client
onCompleteCallback.onQueryResponse(result, nanoAppStateList);
}
}
};
}
NanoAppcreate/Enable/Disable/Load/Unload/Query:Transcation
没有Message传送CreateTransaction
NanoApp load/unload 有old API 两者的区别 NanoApp -> NanoAppBinary, IContextHubTransactionCallback(是否client提供)
loadNanoApp后必须要enable吗?
@Override
public void loadNanoAppOnHub(
int contextHubId, IContextHubTransactionCallback transactionCallback,
NanoAppBinary nanoAppBinary) throws RemoteException {
checkPermissions();
ContextHubServiceTransaction transaction = mTransactionManager.createLoadTransaction(
contextHubId, nanoAppBinary, transactionCallback);
mTransactionManager.addTransaction(transaction);
}
ContextHubServiceTransaction createLoadTransaction(
int contextHubId, NanoAppBinary nanoAppBinary,
IContextHubTransactionCallback onCompleteCallback) {
return new ContextHubServiceTransaction(
mNextAvailableId.getAndIncrement(), ContextHubTransaction.TYPE_LOAD_NANOAPP) {
@Override
/* package */ int onTransact() {
android.hardware.contexthub.V1_0.NanoAppBinary hidlNanoAppBinary =
ContextHubServiceUtil.createHidlNanoAppBinary(nanoAppBinary);
try {
return mContextHubProxy.loadNanoApp(//通过contextHub调用hal: loadNanoApp
contextHubId, hidlNanoAppBinary, this.getTransactionId());
}
}
@Override
/* package */ void onTransactionComplete(@ContextHubTransaction.Result int result) {
if (result == ContextHubTransaction.RESULT_SUCCESS) {
mNanoAppStateManager.addNanoAppInstance(//mNanoAppStateManager维护所有的NanoApp
contextHubId, nanoAppBinary.getNanoAppId(),
nanoAppBinary.getNanoAppVersion());
}
try {
onCompleteCallback.onTransactionComplete(result); //onCompleteCallback:
if (result == ContextHubTransaction.RESULT_SUCCESS) {//
mClientManager.onNanoAppLoaded(contextHubId, nanoAppBinary.getNanoAppId());
}
}
}
};
}
//调用ContextHubManager管理的所有client,分别调用对应的IContextHubClientCallback
void onNanoAppLoaded(int contextHubId, long nanoAppId) {
forEachClientOfHub(contextHubId, client -> client.onNanoAppLoaded(nanoAppId));
}
private void forEachClientOfHub(int contextHubId, Consumer<ContextHubClientBroker> callback) {
for (ContextHubClientBroker broker : mHostEndPointIdToClientMap.values()) {
if (broker.getAttachedContextHubId() == contextHubId) {
callback.accept(broker);
}
}
}
sendMesssage到某个nanoApp
int sendMessage(int contextHubHandle, int nanoAppHandle, in ContextHubMessage msg);
sendMessage
@Override
public int sendMessage(int contextHubHandle, int nanoAppHandle, ContextHubMessage msg)
throws RemoteException {
checkPermissions();
boolean success = false;
if (nanoAppHandle == OS_APP_INSTANCE) {
if (msg.getMsgType() == MSG_QUERY_NANO_APPS) {
success = (queryNanoAppsInternal(contextHubHandle) == Result.OK);
}
} else {nanoAppHandle和AppId()不是同一个东西
NanoAppInstanceInfo info = getNanoAppInstanceInfo(nanoAppHandle);
if (info != null) {
NanoAppMessage message = NanoAppMessage.createMessageToNanoApp(
info.getAppId(), msg.getMsgType(), msg.getData());
IContextHubClient client = mDefaultClientMap.get(contextHubHandle);
success = (client.sendMessageToNanoApp(message) ==
ContextHubTransaction.RESULT_SUCCESS);
}
}
return success ? 0 : -1;
}
IContextHubClient: sendMessageToNanoApp
//调用的 IContextHubClient的 sendMessageToNanoApp接口
public int sendMessageToNanoApp(NanoAppMessage message) {
ContextHubServiceUtil.checkPermissions(mContext);
int result;
if (mConnectionOpen.get()) {
ContextHubMsg messageToNanoApp = ContextHubServiceUtil.createHidlContextHubMessage(
mHostEndPointId, message);
try {//mContextHubProxy
result = mContextHubProxy.sendMessageToHub(mAttachedContextHubId, messageToNanoApp);
}
}
return ContextHubServiceUtil.toTransactionResult(result);
}
来着 context hub的数据到client
hal接口handleClientMsg
public void handleClientMsg(ContextHubMsg message) {
handleClientMessageCallback(mContextHubId, message);
}
private void handleClientMessageCallback(int contextHubId, ContextHubMsg message) {
mClientManager.onMessageFromNanoApp(contextHubId, message);
}
void onMessageFromNanoApp(int contextHubId, ContextHubMsg message) {
NanoAppMessage clientMessage = ContextHubServiceUtil.createNanoAppMessage(message);
if (clientMessage.isBroadcastMessage()) {
broadcastMessage(contextHubId, clientMessage);
} else {//通过hostEndPoint得到ContextHubClientBroker
ContextHubClientBroker proxy = mHostEndPointIdToClientMap.get(message.hostEndPoint);
if (proxy != null) {
proxy.sendMessageToClient(clientMessage);
} else {
Log.e(TAG, "Cannot send message to unregistered client (host endpoint ID = "
+ message.hostEndPoint + ")");
}
}
}
最终调用到client注册的IContextHubClientCallback: onMessageNanoApp
private void broadcastMessage(int contextHubId, NanoAppMessage message) {
forEachClientOfHub(contextHubId, client -> client.sendMessageToClient(message));
}
void sendMessageToClient(NanoAppMessage message) {
if (mConnectionOpen.get()) {
try {
mCallbackInterface.onMessageFromNanoApp(message);
}
}
}