> For AI agents: the complete documentation index is available at /next/zh/llms.txt, the full documentation bundle is available at /next/zh/llms-full.txt.

# LynxService API

APISummary
## 能力简介

Lynx Service 为 Lynx Engine 提供了宿主特性相关能力，包括图片、日志和 [FetchAPI](/next/zh/guide/interaction/networking.md#使用-fetch) 相关能力。
不同的接入方对自身的图片库、日志库和网络库有特定的需求，因此 Lynx Engine 通过 LynxService API 对外开放了针对这类场景的自主接入能力。

## 整体设计

Lynx Engine 和 Lynx Service 采用依赖分离设计；从依赖关系上看，Lynx Service 实现了 Lynx Engine 暴露的 LynxService API，而 Lynx Engine 不依赖 Lynx Service。在运行时 Lynx Engine 会通过服务查找机制查找注册的 Lynx Service，并通过 LynxService API 调用。

## LynxService API

LynxService API 是 Lynx Engine 提供的，用于指定 Lynx Service 能力的 API 设计。Lynx Service 需要依照 LynxService API 的要求正确的实现自身，以确定 Lynx Engine 能正确的使用该基础能力。

## 1. 快速接入

Lynx 提供了 Lynx Service 的默认实现，可以直接[接入](/next/zh/guide/start/integrate-with-existing-apps.md)

## 2. 扩展 Lynx Service

如果有自定义需求，也可以根据自身需求快速实现并注册相关内容。下面将以 log service 为例，介绍如何实现并接入自定义的 Lynx Service：

### 接口实现

**iOS**

- 1. 实现 `LynxServiceLogProtocol`

```objective-c title="YourLogService.h"
#import <Lynx/LynxService.h>
#import <Lynx/LynxServiceLogProtocol.h>

// 实现 LynxServiceLogProtocol
@interface YourLogService : NSObject <LynxServiceLogProtocol>
@end
```

- 2. 通过 `LynxServiceRegister` 宏实现自动注册；
- 3. 实现 `serviceBizID`，`serviceScope`。这两个方法没有实际意义，后续会被删除；
- 4. 实现 `serviceType`。需返回该 Service 所实现的类型，详见 Lynx Service.h；
- 5. (推荐) 实现 `sharedInstance`，成为单例类。基于目前的 Lynx Service 设计，一个类型的 Service 全局只会使用一个实例，建议实现为单例类；
- 6. 实现 `LynxServiceLogProtocol` 要求的全部接口；

```objective-c title="YourLogService.mm"
#import "YourLogService.h"

[[maybe_unused]] void logWrite(unsigned int level, const char *tag, const char *format) {
  if (format == NULL) {
    return;
  }
  NSLog(@"[%s] %s", tag == NULL ? "" : tag, format);
}

// 通过 LynxServiceRegister 宏实现自动注册
@LynxServiceRegister(LynxLogService);

// 实现 LynxLogService
@implementation LynxLogService

// 无关属性，后续会删除
+ (NSString*)serviceBizID {
  return DEFAULT_LYNX_SERVICE;
}

// 无关属性，后续会删除
+ (Lynx ServiceScope)serviceScope {
  return Lynx ServiceScopeDefault;
}

// 返回对应 service type, 实现远行时查找
+ (NSUInteger)serviceType {
  return kLynxServiceLog;
}

// 推荐：实现为单例
+ (instancetype)sharedInstance {
  static dispatch_once_t onceToken;
  static YourLogService *logService;
  dispatch_once(&onceToken, ^{
    logService = [[YourLogService alloc] init];
  });
  return logService;
}

// 实现 LynxServiceLogProtocol 要求的全部接口
- (void *)getWriteFunction {
  return (void *)lynx::base::logging::logWrite;
}

@end
```

**Android**

实现 `ILynxLogService`：

```kotlin title="YourLogService.kt"
object YourLogService : ILynxLogService {
  private var logOutputChannel: LogOutputChannelType = LogOutputChannelType.Platform

  override fun logByPlatform(
    level: Int,
    tag: String,
    msg: String,
  ) {
    // 具体实现
  }

  override fun isLogOutputByPlatform(): Boolean = logOutputChannel == LogOutputChannelType.Platform

  override fun getDefaultWriteFunction(): Long = 0

  override fun switchLogToSystem(enableSystemLog: Boolean) {}

  override fun getLogToSystemStatus(): Boolean = false
}
```

**Harmony**

实现 `ILynxLogService`：

```typescript title="YourLogService.ets"
import { ILynxLogService } from '@lynx/lynx';

export class YourLogService implements ILynxLogService {
  static instance = new YourLogService();

  logByPlatform(level: number, tag: string, message: string): void {
    console.log(`level: ${level} tag: ${tag} message: ${message}`);
  }

  isLogOutputByPlatform(): boolean {
    return true;
  }

  getDefaultWriteFunction(): number {
    return 0;
  }
}
```

**Desktop C++**

实现一个具体的 Desktop service 类。下面以 `LynxHttpService` 为例；`LynxSecurityService` 和 `LynxEventReporterService` 也是同样模式，只是分别重写自己的抽象入口。

```cpp title="YourHttpService.h"
#include "lynx/platform/embedder/public/lynx_http_service.h"

class YourHttpService : public lynx::pub::LynxHttpService {
 public:
  void Request(std::shared_ptr<lynx::pub::LynxHttpRequest> request,
               std::shared_ptr<lynx::pub::LynxHttpResponse> response) override {
    response->SetStatusCode(200);
    response->SetStatusText("OK");
    response->Complete();
  }
};
```

不同 service type 对应的实现入口分别是：

- `LynxHttpService`: 重写 `Request(...)`
- `LynxSecurityService`: 重写 `VerifyTASM(...)`
- `LynxEventReporterService`: 重写 `OnEvent(...)`


### 服务注册

**iOS**

Lynx Service 在 iOS 中有自动注册机制。在实现阶段，`LynxServiceRegister` 宏已用于完成快速自动注册。

如果您使用自己实现的 Lynx Service，请删除 Lynx 提供的[默认实现](/next/zh/guide/start/integrate-with-existing-apps.md?platform=ios)。

```diff title="Podfile" {1-5}
pod 'LynxService', '4.2.0', :subspecs => [
      'Image',
-     'Log',
      'Http',
  ]
```

**Android**

在[集成文档](/next/zh/guide/start/integrate-with-existing-apps.md?platform=android)中，将 `LynxServiceCenter` 中的日志服务实现替换为您的实现。

```diff
- LynxServiceCenter.inst().registerService(ILynxLogService::class.java, LynxLogService)
+ LynxServiceCenter.inst().registerService(ILynxLogService::class.java, YourLogService)
```

并删除相关依赖

```diff title="build.gradle"
dependencies {
-   // 集成日志服务
-   implementation "org.lynxsdk.lynx:lynx-service-log:4.2.0"
}
```

**Harmony**

在[集成文档](/next/zh/guide/start/integrate-with-existing-apps.md?platform=harmony)中，将 `LynxServiceCenter` 中的日志服务实现替换为您的实现。

```diff
- LynxServiceCenter.registerService(LynxServiceType.Log, LynxLogService.instance);
+ LynxServiceCenter.registerService(LynxServiceType.Log, YourLogService.instance);
```

并删除相关依赖

```diff title="oh-package.json5"
"dependencies": {
- "@lynx/lynx_log_service": "4.2.0",
}
```

**Desktop C++**

通过 `LynxServiceCenter` 注册已经实现好的 service：

```cpp
auto service = std::make_shared<YourHttpService>();
lynx::pub::LynxServiceCenter::GetInstance().RegisterService(service);
```

最终注册到哪个 service type，由具体 service 类决定：

- `LynxHttpService` -> `kServiceTypeHttp`
- `LynxSecurityService` -> `kServiceTypeSecurity`
- `LynxEventReporterService` -> `kServiceTypeEventReporter`


**Compatibility Table**

**Query:** `lynx-native-api.lynx-service.lynx-service`

[Source](https://github.com/lynx-family/lynx-website/tree/main/packages/lynx-compat-data/lynx-native-api/lynx-service/lynx-service.json)

| Feature | Android | HarmonyOS | iOS | macOS | Windows | Web |
| --- | --- | --- | --- | --- | --- | --- |
| lynx-service | Yes (2.8) | Yes (3.4) | Yes (2.8) | Yes (3.7) | Yes (3.7) | No |

**`lynx-service`**

LynxService API

**Specifications:**

