記錄事件

您可以透過事件深入分析應用程式情況,例如使用者動作、系統事件或錯誤。

Google Analytics (分析) 會自動記錄部分事件,您不需要新增任何程式碼就能接收事件。如果應用程式需要收集其他資料,您最多可以在應用程式中記錄 500 種不同的 Analytics (分析) 事件類型。應用程式記錄的事件總數沒有上限。請注意,事件名稱有大小寫之分,且記錄的兩個事件名稱只有在不同情況下才會產生兩個不同的事件。

事前準備

請確認您已按照「開始使用適用於 C++ 的 Analytics (分析)」中的說明設定專案,並能存取 Analytics (分析)。

記錄事件

初始化 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 是一般用途參數,可用來累積與 Analytics (分析) 事件相關的重要指標。例如收益、距離、時間和點數。

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

// 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」(分析),即可查看 Analytics (分析) 報表資訊主頁。

「事件」分頁會顯示系統為應用程式記錄的每種 Analytics (分析) 事件自動建立的事件報表。進一步瞭解資訊主頁