> For the complete documentation index, see [llms.txt](https://portal-integracao.intelbras.com.br/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://portal-integracao.intelbras.com.br/linha-android/algoritimos-e-funcionamento/armazenamento-na-memoria-de-caracteristicas-de-face.md).

# Armazenamento na Memória de Características de Face

## Armazenamento na Memória de Características de Face

### Carregamento dos dados persistentes na memória

1. Algoritmo de inicialização（Código de referência startAlgorithm()）
2. Crie um banco de dados de cache de memória de valores de recursos faciais （Código de referência createFaceFeatureDB()）
3. Carregue todos os valores de recursos faciais existentes no cache de memória （Código de referência loadFaceFeatureIntoMemory()）

Geralmente, nenhuma manutenção é necessária para a parte de acesso. O processo completo de carregamento persistente do banco de dados é detalhado em LamyAiServer. O design de banco de dados persistente de valor de recurso facial pode referir-se a DataBaseHelperManager

### Memory cache operation

```java
/**
 * The call has a very high priority and can be placed asynchronously in the
 * MainApplication
 */
private void startAlgorithm() {
    handlerThread = new HandlerThread("qbic-listener");
    handlerThread.start();
    mQbicHandler = new Handler(handlerThread.getLooper());
    mAiFaceFeatureQbicProxy = new AiFaceFeatureQbicProxy(handlerThread.getLooper());
    // It is necessary to set the memory cache exception monitoring to avoid that
    // the feature value in the memory does not exist after the memory cache is
    // abnormal, resulting in the abnormal face recognition
    mAiFaceFeatureQbicProxy.setQbicListener(new AiFaceFeatureQbicProxy.FaceFeatureQbicListener() {
        @Override
        public void onError(int errorType) {
            ModuleLog.e(TAG, "onError: errorType=" + errorType);
            if (errorType == AiServerErrorType.ERROR_RELOAD_FACE_DB.getValue()) {
                // need load all face feature into memory cache
                loadFaceFeatureIntoMemory();
            }
        }
    });
    // Startup algorithm
    boolean result = mAiFaceFeatureQbicProxy.start();
    ModuleLog.e(TAG, "initData: mAiFaceQbicProxy.start=" + result);
}

/**
 * Generally do not need to call separately, after the destruction of memory
 * there is no face
 * characteristic value, face recognition is not successful
 */
private void destroyFaceFeatureDB() {
    int result = mAiFaceFeatureQbicProxy.destroyFeatureDB();
    ModuleLog.e(TAG, "destroyFaceFeatureDB: result=" + result);
    if (JniResultCode.isSuccess(result)) {
        showToast("destroyFaceFeatureDB Success");
    } else {
        showToast("destroyFaceFeatureDB fail.");
    }
}

/**
 * Add feature values to the memory cache
 */
private synchronized boolean addFaceInfo2MemoryCache(int faceId, String userName) {
    boolean result = false;
    if (mFaceFeature != null) {
        if (mAiFaceFeatureQbicProxy == null) {
            mAiFaceFeatureQbicProxy = new AiFaceFeatureQbicProxy();
            mAiFaceFeatureQbicProxy.start();
        }
        // Create it once
        int resultCode = mAiFaceFeatureQbicProxy.createFeatureDB();
        ModuleLog.i(TAG, "addFaceInfo2MemoryCache: createFeatureDB. resultCode=" + resultCode);
        // The feature id can be customized but cannot be repeated.
        // To avoid adding the same faceId multiple times, delete the FaceID before
        // adding it. Otherwise, the FaceID will be deleted and an exception will be
        // identified
        // If you are sure that the faceId has been added, you can use updateFeature(),
        // which performs much worse than the insertFeature() interface
        resultCode = mAiFaceFeatureQbicProxy.insertFeature(mFaceFeature, faceId);
        ModuleLog.i(TAG, "addFaceInfo2MemoryCache: insertFeature. faceId=" + faceId + ",    resultCode=" + resultCode);
        if (JniResultCode.isSuccess(resultCode)) {
            showToast("addFaceInfo2MemoryCache Success, faceId " + faceId + ", user name " +
                    userName);
            result = true;
        } else {
            showToast("addFaceInfo2MemoryCache fail.");
        }
    } else {
        showToast("Please collect face first.");
    }
    return result;
}

/**
 * Deletes a feature value from the memory cache
 */
private void deleteFaceInfo() {
    String strFaceId = String.valueOf(mFaceId.getText());
    if (TextUtils.isEmpty(strFaceId)) {
        showToast(R.string.pls_input_face_id);
        return;
    }
    int faceId = Integer.parseInt(strFaceId);
    // Deletes a feature value from the persistent database
    DemoApplication.deleteDbFaceByFaceId(faceId);
    // Deletes a feature value from the memory cache
    mAiFaceFeatureQbicProxy.deleteFeature(faceId);
}

/**
 * Remove all feature value information from the memory cache
 * 3.6 Face ID Card Recognition
 * At present, the supported Face ID Card Recognition is mixed identification,
 * that is,
 * priority Face ID Card Recognition, if there is no ID card information, then
 * go face recognition
 * The similarity threshold of Face ID Card Recognition is maintained by the
 * service itself,
 * and the ai service does not need to be used.
 * For details, see the demo AiFaceCardRecognitionActivity
 * 3.6.1Startup algorithm
 */
private void deleteAllFaceInfo() {
    // Delete the persistent database
    DemoApplication.deleteAllFeature();
    // Compatibility scheme: After the database is destroyed, you need to recreate
    // the database
    int resultCode = mAiFaceFeatureQbicProxy.destroyFeatureDB();
    ModuleLog.e(TAG, "deleteAllFaceInfo: destroyFeatureDB resultCode=" + resultCode);
    resultCode = mAiFaceFeatureQbicProxy.createFeatureDB();
    ModuleLog.e(TAG, "deleteAllFaceInfo: createFeatureDB resultCode=" + resultCode);
    if (JniResultCode.isSuccess(resultCode)) {
        showToast("deleteAllFaceInfo Success");
    } else {
        showToast("deleteAllFaceInfo fail.");
    }
}

/**
 * Extract face feature value
 * The access party determines whether persistence is required based on service
 * requirements
 */
private void getImageFeature() {
    mFaceFeatureBytes = LamyAiServerClientProxy.getInstance().getFaceFeatureWithRgb("",
            mFaceImageBytes);
    if (mFaceFeatureBytes == null) {
        ModuleLog.e(TAG, "getImageFeature: failed.");
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://portal-integracao.intelbras.com.br/linha-android/algoritimos-e-funcionamento/armazenamento-na-memoria-de-caracteristicas-de-face.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
