記錄事件

事件可讓您深入了解應用程式中發生的情況,例如使用者操作、系統事件或錯誤。

Google Analytics 會自動為您記錄一些事件;您無需添加任何代碼即可接收它們。如果您的應用程式需要收集其他數據,您可以在應用程式中記錄最多 500 個不同的 Analytics 事件類型。您的應用程式記錄的事件總量沒有限制。請注意,事件名稱區分大小寫,記錄名稱僅大小寫不同的兩個事件會導致兩個不同的事件。

在你開始之前

確保您已設定專案並可以存取 Analytics,如C++ 分析入門中所述。

記錄事件

初始化firebase::analytics模組後,您可以使用它透過LogEvent()方法記錄事件。

為了幫助您入門,Analytics SDK 定義了許多不同類型應用程式(包括零售和電子商務、旅遊和遊戲應用程式)中常見的推薦事件。要了解有關這些事件以及何時使用它們的更多信息,請瀏覽 Firebase 幫助中心中的事件和屬性文章。

您可以在以下位置找到推薦事件的實施詳細資訊:

  • 建議的事件:請參閱Event常數清單。
  • 規定參數:請參閱Parameters常數列表。

以下範例示範如何記錄建議的SELECT_CONTENT事件:

  const analytics::Parameter kSelectContentParameters[] = {
    analytics::Parameter(analytics::kParameterItemID , id),
    analytics::Parameter(analytics::kParameterItemName, "name"),
    analytics::Parameter(analytics::kUserPropertySignUpMethod, "Google"),
    analytics::Parameter("favorite_food", mFavoriteFood),
    analytics::Parameter("user_id", mUserId),
  };
  analytics::LogEvent(
    analytics::kEventSelectContent, kSelectContentParameters,
    sizeof(kSelectContentParameters) / sizeof(kSelectContentParameters[0]));

除了規定的參數之外,您還可以將以下參數新增至任何事件:

  • 自訂參數:自訂參數不會直接在您的 Analytics 報告中表示,但它們可以用作受眾定義中的過濾器,並應用於每個報告。如果您的應用程式連結到 BigQuery 項目,自訂參數也會包含在匯出到 BigQuery 的資料中。

  • VALUE參數: VALUE是通用參數,可用來累積與分析事件相關的關鍵指標。例如收入、距離、時間和積分。

如果您的應用程式具有建議的分析事件類型未涵蓋的特定需求,您可以記錄您自己的自訂分析事件,如下例所示:

// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "firebase/analytics.h"
#include "firebase/analytics/event_names.h"
#include "firebase/analytics/parameter_names.h"
#include "firebase/analytics/user_property_names.h"
#include "firebase/app.h"

// Thin OS abstraction layer.
#include "main.h"  // NOLINT

// Execute all methods of the C++ Analytics API.
extern "C" int common_main(int argc, const char* argv[]) {
  namespace analytics = ::firebase::analytics;
  ::firebase::App* app;

  LogMessage("Initialize the Analytics library");
#if defined(__ANDROID__)
  app = ::firebase::App::Create(GetJniEnv(), GetActivity());
#else
  app = ::firebase::App::Create();
#endif  // defined(__ANDROID__)

  LogMessage("Created the firebase app %x",
             static_cast<int>(reinterpret_cast<intptr_t>(app)));
  analytics::Initialize(*app);
  LogMessage("Initialized the firebase analytics API");

  LogMessage("Enabling data collection.");
  analytics::SetAnalyticsCollectionEnabled(true);
  // App session times out after 30 minutes.
  // If the app is placed in the background and returns to the foreground after
  // the timeout is expired analytics will log a new session.
  analytics::SetSessionTimeoutDuration(1000 * 60 * 30);

  LogMessage("Get App Instance ID...");
  auto future_result = analytics::GetAnalyticsInstanceId();
  while (future_result.status() == firebase::kFutureStatusPending) {
    if (ProcessEvents(1000)) break;
  }
  if (future_result.status() == firebase::kFutureStatusComplete) {
    LogMessage("Analytics Instance ID %s", future_result.result()->c_str());
  } else {
    LogMessage("ERROR: Failed to fetch Analytics Instance ID %s (%d)",
               future_result.error_message(), future_result.error());
  }

  LogMessage("Set user properties.");
  // Set the user's sign up method.
  analytics::SetUserProperty(analytics::kUserPropertySignUpMethod, "Google");
  // Set the user ID.
  analytics::SetUserId("uber_user_510");

  LogMessage("Log current screen.");
  // Log the user's current screen.
  analytics::LogEvent(analytics::kEventScreenView, "Firebase Analytics C++ testapp", "testapp" );

  // Log an event with no parameters.
  LogMessage("Log login event.");
  analytics::LogEvent(analytics::kEventLogin);

  // Log an event with a floating point parameter.
  LogMessage("Log progress event.");
  analytics::LogEvent("progress", "percent", 0.4f);

  // Log an event with an integer parameter.
  LogMessage("Log post score event.");
  analytics::LogEvent(analytics::kEventPostScore, analytics::kParameterScore,
                      42);

  // Log an event with a string parameter.
  LogMessage("Log group join event.");
  analytics::LogEvent(analytics::kEventJoinGroup, analytics::kParameterGroupID,
                      "spoon_welders");

  // Log an event with multiple parameters.
  LogMessage("Log level up event.");
  {
    const analytics::Parameter kLevelUpParameters[] = {
        analytics::Parameter(analytics::kParameterLevel, 5),
        analytics::Parameter(analytics::kParameterCharacter, "mrspoon"),
        analytics::Parameter("hit_accuracy", 3.14f),
    };
    analytics::LogEvent(
        analytics::kEventLevelUp, kLevelUpParameters,
        sizeof(kLevelUpParameters) / sizeof(kLevelUpParameters[0]));
  }

  LogMessage("Complete");

  // Wait until the user wants to quit the app.
  while (!ProcessEvents(1000)) {
  }

  analytics::Terminate();
  delete app;

  LogMessage("Shutdown");

  return 0;
}

查看 Android Studio 偵錯日誌中的事件

您可以啟用詳細日誌記錄以監視 SDK 的事件記錄,以協助驗證事件是否已正確記錄。這包括自動和手動記錄的事件。

您可以使用一系列 adb 指令啟用詳細日誌記錄:

adb shell setprop log.tag.FA VERBOSE
adb shell setprop log.tag.FA-SVC VERBOSE
adb logcat -v time -s FA FA-SVC

此命令會在 Android Studio logcat 中顯示您的事件,幫助您立即驗證事件是否正在傳送。

在儀表板中查看分析事件

您可以在 Firebase 控制台儀表板中查看有關 Analytics 事件的總計統計資料。這些儀表板全天定期更新。若要立即進行測試,請使用上一節所述的 logcat 輸出。

要在 Firebase 控制台中存取此資料:

  1. Firebase 控制台中,開啟您的專案。
  2. 從選單中選擇“分析”以查看“分析”報告儀表板。

「事件」標籤顯示為您的應用程式記錄的每種不同類型的 Analytics 事件自動建立的事件報告。閱讀有關儀表板的更多資訊。