Google Analytics會自動記錄部分事件,您無需新增任何程式碼即可接收這些事件。如果應用程式需要收集額外資料,最多可在應用程式中記錄 500 種不同的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"intcommon_main(intargc,constchar*argv[]){namespaceanalytics=::firebase::analytics;::firebase::App*app;LogMessage("Initialize the Analytics library");#if defined(__ANDROID__)app=::firebase::App::Create(GetJniEnv(),GetActivity());#elseapp=::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...");autofuture_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.");{constanalytics::ParameterkLevelUpParameters[]={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();deleteapp;LogMessage("Shutdown");return0;}
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-09-03 (世界標準時間)。"],[],[],null,["\u003cbr /\u003e\n\nEvents provide insight on what is happening in your app, such as user\nactions, system events, or errors.\n\nGoogle Analytics automatically logs some\n[events](https://support.google.com/analytics/answer/6317485) for you;\nyou don't need to add any code to receive them. If your app needs to collect\nadditional data, you can log up to 500 different Analytics event types\nin your app. There is no limit on the total volume of events your app logs.\nNote that event names are case-sensitive and that logging two events whose\nnames differ only in case results in two distinct events.\n\nBefore you begin\n\nMake sure that you've set up your project and can access Analytics as\ndescribed in\n[Get Started with Analytics for C++](/docs/analytics/cpp/start#before_you_begin).\n\nLog events\n\nAfter you have initialized the `firebase::analytics` module, you can use it to log\nevents with the [`LogEvent()`](/docs/reference/cpp/namespace/firebase/analytics#logevent) method.\n\nTo help you get started, the Analytics SDK defines a number of\nrecommended events that are common among different types of apps, including\nretail and ecommerce, travel, and gaming apps. To learn more about these events\nand when to use them, browse the [Events and properties](https://support.google.com/analytics/answer/9267735)\narticles in the Firebase Help Center.\n| **Note:** To get the maximum detail in reports, log the suggested Analytics Events that make sense for your app and their prescribed parameters. This also ensures that you benefit from the latest Google Analytics features as they become available.\n\nYou can find implementation details for recommended events in the following\nlocations:\n\n- Suggested events: see the list of [`Event`](/docs/reference/cpp/group/event-names) constants.\n- Prescribed parameters: see the list of [`Parameters`](/docs/reference/cpp/group/parameter-names) constants.\n\nThe following example demonstrates how to log a suggested\n[`SELECT_CONTENT`](/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event#SELECT_CONTENT) Event: \n\n```c++\n const analytics::Parameter kSelectContentParameters[] = {\n analytics::Parameter(analytics::kParameterItemID , id),\n analytics::Parameter(analytics::kParameterItemName, \"name\"),\n analytics::Parameter(analytics::kUserPropertySignUpMethod, \"Google\"),\n analytics::Parameter(\"favorite_food\", mFavoriteFood),\n analytics::Parameter(\"user_id\", mUserId),\n };\n analytics::LogEvent(\n analytics::kEventSelectContent, kSelectContentParameters,\n sizeof(kSelectContentParameters) / sizeof(kSelectContentParameters[0]));\n```\n\nIn addition to the prescribed parameters, you can add the following parameters\nto any event:\n\n- Custom parameters: Custom parameters are not represented directly in your\n Analytics reports, but they can be used as filters in\n [Audience](https://support.google.com/firebase/answer/6317509) definitions that can be applied to every report. Custom\n parameters are also included in data [exported to BigQuery](https://support.google.com/firebase/answer/6318765) if\n your app is linked to a BigQuery project.\n\n- `VALUE` Parameter: [`VALUE`](/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Param#VALUE) is a general purpose parameter\n that is useful for accumulating a key metric that pertains to an\n Analytics Event. Examples include revenue, distance, time and points.\n\nIf your application has specific needs not covered by a suggested\nAnalytics Event type, you can log your own custom Analytics Events\nas shown in this example: \n\n```c++\n// Copyright 2016 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"firebase/analytics.h\"\n#include \"firebase/analytics/event_names.h\"\n#include \"firebase/analytics/parameter_names.h\"\n#include \"firebase/analytics/user_property_names.h\"\n#include \"firebase/app.h\"\n\n// Thin OS abstraction layer.\n#include \"main.h\" // NOLINT\n\n// Execute all methods of the C++ Analytics API.\nextern \"C\" int common_main(int argc, const char* argv[]) {\n namespace analytics = ::firebase::analytics;\n ::firebase::App* app;\n\n LogMessage(\"Initialize the Analytics library\");\n#if defined(__ANDROID__)\n app = ::firebase::App::Create(GetJniEnv(), GetActivity());\n#else\n app = ::firebase::App::Create();\n#endif // defined(__ANDROID__)\n\n LogMessage(\"Created the firebase app %x\",\n static_cast\u003cint\u003e(reinterpret_cast\u003cintptr_t\u003e(app)));\n analytics::Initialize(*app);\n LogMessage(\"Initialized the firebase analytics API\");\n\n LogMessage(\"Enabling data collection.\");\n analytics::SetAnalyticsCollectionEnabled(true);\n // App session times out after 30 minutes.\n // If the app is placed in the background and returns to the foreground after\n // the timeout is expired analytics will log a new session.\n analytics::SetSessionTimeoutDuration(1000 * 60 * 30);\n\n LogMessage(\"Get App Instance ID...\");\n auto future_result = analytics::GetAnalyticsInstanceId();\n while (future_result.status() == firebase::kFutureStatusPending) {\n if (ProcessEvents(1000)) break;\n }\n if (future_result.status() == firebase::kFutureStatusComplete) {\n LogMessage(\"Analytics Instance ID %s\", future_result.result()-\u003ec_str());\n } else {\n LogMessage(\"ERROR: Failed to fetch Analytics Instance ID %s (%d)\",\n future_result.error_message(), future_result.error());\n }\n\n LogMessage(\"Set user properties.\");\n // Set the user's sign up method.\n analytics::SetUserProperty(analytics::kUserPropertySignUpMethod, \"Google\");\n // Set the user ID.\n analytics::SetUserId(\"uber_user_510\");\n\n LogMessage(\"Log current screen.\");\n // Log the user's current screen.\n analytics::LogEvent(analytics::kEventScreenView, \"Firebase Analytics C++ testapp\", \"testapp\" );\n\n // Log an event with no parameters.\n LogMessage(\"Log login event.\");\n analytics::LogEvent(analytics::kEventLogin);\n\n // Log an event with a floating point parameter.\n LogMessage(\"Log progress event.\");\n analytics::LogEvent(\"progress\", \"percent\", 0.4f);\n\n // Log an event with an integer parameter.\n LogMessage(\"Log post score event.\");\n analytics::LogEvent(analytics::kEventPostScore, analytics::kParameterScore,\n 42);\n\n // Log an event with a string parameter.\n LogMessage(\"Log group join event.\");\n analytics::LogEvent(analytics::kEventJoinGroup, analytics::kParameterGroupID,\n \"spoon_welders\");\n\n // Log an event with multiple parameters.\n LogMessage(\"Log level up event.\");\n {\n const analytics::Parameter kLevelUpParameters[] = {\n analytics::Parameter(analytics::kParameterLevel, 5),\n analytics::Parameter(analytics::kParameterCharacter, \"mrspoon\"),\n analytics::Parameter(\"hit_accuracy\", 3.14f),\n };\n analytics::LogEvent(\n analytics::kEventLevelUp, kLevelUpParameters,\n sizeof(kLevelUpParameters) / sizeof(kLevelUpParameters[0]));\n }\n\n LogMessage(\"Complete\");\n\n // Wait until the user wants to quit the app.\n while (!ProcessEvents(1000)) {\n }\n\n analytics::Terminate();\n delete app;\n\n LogMessage(\"Shutdown\");\n\n return 0;\n}\n```\n\nView events in the Android Studio debug log\n\nYou can enable verbose logging to monitor logging of events by the SDK to help\nverify that events are being logged properly. This includes both automatically\nand manually logged events.\n\nYou can enable verbose logging with a series of adb commands:\n\n\u003cbr /\u003e\n\n```\nadb shell setprop log.tag.FA VERBOSE\n``` \n\n```\nadb shell setprop log.tag.FA-SVC VERBOSE\n``` \n\n```\nadb logcat -v time -s FA FA-SVC\n```\n\n\u003cbr /\u003e\n\nThis command displays your events in the Android Studio logcat, helping you\nimmediately verify that events are being sent.\n\nView analytics events in the dashboard\n\nYou can view aggregated statistics about your Analytics events in the\nFirebase console dashboards. These dashboards update periodically\nthroughout the day. For immediate testing, use the logcat output as described in\nthe previous section.\n\nTo access this data in the Firebase console:\n\n1. In the [Firebase console](//console.firebase.google.com/), open your project.\n2. Select **Analytics** from the menu to view the Analytics reporting dashboard.\n\nThe **Events** tab shows the event reports that are\nautomatically created for each distinct type of Analytics event logged by\nyour app. Read more about the [dashboard](https://support.google.com/analytics/answer/11014767)."]]