> ## Documentation Index
> Fetch the complete documentation index at: https://docs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 如何使用 XBOX 服务 API

> 介绍如何初始化 Gaming Runtime Services (GRTS)、创建 `XTaskQueue`、设置 `HttpClient` 跟踪、初始化 XBOX Services API (XSAPI) 以及清理 XSAPI。

## 初始化 Gaming Runtime Services

XSAPI 依赖于 Gaming Runtime Services (GRTS)。在调用任何 XSAPI 之前，请先初始化 GRTS，如下所示。

```cpp theme={null}
#include <XGameRuntimeInit.h>
...
HRESULT hr = XGameRuntimeInitialize();
```

## 创建 XTaskQueue（可选）

大多数 XSAPI 都是异步 API，需要使用任务队列。它是一个用于将工作排队和用于完成任务回调的 API。要了解有关 `XTaskQueue` 和不同分派模式的更多信息，请参阅 [异步任务队列设计](https://docs.xbox.com/zh-CN/build/core-features/common/async/async-task-queue-design.md)。

例如，以下代码使用系统线程池创建任务队列。

```cpp theme={null}
#include <XTaskQueue.h>
...
XTaskQueueHandle queue = nullptr;

HRESULT hr = XTaskQueueCreate(
    XTaskQueueDispatchMode::ThreadPool,
    XTaskQueueDispatchMode::ThreadPool,
    &queue)
```

确保在不再需要获取的任务队列句柄时将其释放回系统。

```cpp theme={null}
XTaskQueueCloseHandle(queue);
queue = nullptr;
```

如果你选择不创建自己的任务队列，则在需要队列句柄时请确保传入 `nullptr`。当使用 `nullptr` 时，任务系统默认使用 `ThreadPool`。可以通过调用 [XTaskQueueSetCurrentProcessTaskQueue](https://docs.xbox.com/zh-CN/reference/system/xtaskqueue/functions/xtaskqueuesetcurrentprocesstaskqueue.md) 来重写它。

## 设置 HttpClient 跟踪（可选）

要查看其他运行时调试信息，请确保设置 `HttpClient` 的跟踪功能。

以下代码设置 `HttpClient` 跟踪级别并启用调试器信息的输出。

```cpp theme={null}
HCSettingsSetTraceLevel(HCTraceLevel::Verbose);
HCTraceSetTraceToDebugger(true);
```

## 初始化 XSAPI

在调用任何 XSAPI 之前，*初始化 XSAPI*。

```cpp theme={null}
#include <xsapi-c/services-c.h>
...
XblInitArgs xblArgs = {};
xblArgs.queue = queue; // TODO: Only include this line if you've chosen to create your own XTaskQueue. Otherwise, by default, this line isn't needed.
xblArgs.scid = "00000000-0000-0000-0000-000000000000"; // TODO: Add your scid here.

HRESULT hr = XblInitialize(&xblArgs);
if (FAILED(hr))
{
    // TODO: Handle failure.
}
```

## 将用户登录到 XBOX 网络

大多数 XSAPI 都要求用户先登录到 XBOX 网络。\
要将用户登录到 XBOX 网络，请参阅 [XUserAddAsync API](https://docs.xbox.com/zh-CN/build/core-features/common/user/xuser_howto_best_practice_signing_in.md) 的代码示例。

## 创建 XboxLiveContext 对象

`XboxLiveContext` 对象表示与特定用户关联的服务上下文。

大多数 XSAPI 要求你传入表示调用用户上下文的 `XboxLiveContextHandle`。\
要创建 XBOX Live（网络）上下文，请使用 [XblContextCreateHandle API](https://docs.xbox.com/zh-CN/reference/live/xsapi-c/xbox_live_context_c/functions/xblcontextcreatehandle.md)，并传入从上一步获取的 `XUserHandle` 对象。

## 向 XBOX 服务进行服务调用

现在你已有与已登录用户的 `XUserHandle` 对象关联的 `XboxLiveContext` 对象，就可以向 XBOX 服务进行服务调用了。

例如，要检索用户的好友列表，你可以执行以下操作：

```cpp theme={null}
#include <xsapi-c/services-c.h>
...
auto asyncBlock = std::make_unique<XAsyncBlock>(); 
asyncBlock->callback = [](XAsyncBlock* asyncBlock)
{
    std::unique_ptr<XAsyncBlock> asyncBlockPtr{ asyncBlock }; // Take over ownership of the XAsyncBlock*.

    XblSocialRelationshipResultHandle relationshipResult{ nullptr };
    HRESULT hr = XblSocialGetSocialRelationshipsResult(asyncBlock, &state.socialResultHandle);

    // Use the result in the game.

    XblSocialRelationshipResultCloseHandle(relationshipResult);
};

HRESULT hr = XblSocialGetSocialRelationshipsAsync(
    xboxLiveContext,
    xboxUserId,
    socialRelationshipFilter,
    0,
    0,
    asyncBlock.get()
);

if (SUCCEEDED(hr))
{
    // The call succeeded. Release the std::unique_ptr ownership of XAsyncBlock* because the callback will take over ownership.
    // If the call fails, the std::unique_ptr will keep ownership and delete the XAsyncBlock*.
    asyncBlock.release();
}
// End of code example.
```

## 清理 XSAPI

在任何情况下都无需调用 `XblCleanupAsync()`。

在应用终止的情况下，目前没有可调用的同步 `XblCleanup()` API。就其生命周期性质而言，应用终止需要同步且立即地处理。因此，会依赖常规的操作系统级清理—即应用进程终止时发生的清理—这对于此情况已经足够。

在应用挂起的情况下，XSAPI 会处理运行所需系统资源的释放和还原，以便在恢复后保持功能。

如果你的游戏选择主动释放分配给 XSAPI 的资源，仍可以使用 `XblCleanupAsync()`。


## Related topics

- [XSAPI C 概述](https://docs.xbox.com/zh-CN/services/xbox-services/fundamentals/xbox-services-api/live-xsapi-flat-c.md)
- [丰富在线状态概述](https://docs.xbox.com/zh-CN/services/xbox-services/community/presence/live-presence-overview.md)
- [获取基于事件的统计信息](https://docs.xbox.com/zh-CN/services/xbox-services/player-data/stats-leaderboards/event-based/how-to/live-getting-eb-stat.md)
- [XblContextCreateHandle](https://docs.xbox.com/zh-CN/reference/live/xsapi-c/xbox_live_context_c/functions/xblcontextcreatehandle.md)
- [XblInitialize](https://docs.xbox.com/zh-CN/reference/live/xsapi-c/xbox_live_global_c/functions/xblinitialize.md)
