您可以使用 Firebase Remote Config 在應用程式中定義參數,並在雲端更新參數值,不必發布應用程式更新,就能修改應用程式的外觀和行為。
Remote Config 程式庫可用於儲存應用程式內預設參數值、從 Remote Config 後端擷取更新的參數值,以及控管擷取的值何時可供應用程式使用。詳情請參閱「遠端設定載入策略」。
步驟 1:將 Firebase 新增至應用程式
如要使用 Remote Config, 請先完成下列步驟:
註冊 C++ 專案,並設定使用 Firebase。
如果 C++ 專案已使用 Firebase,則已註冊並設定 Firebase。
將 Firebase C++ SDK 新增至 C++ 專案。
請注意,將 Firebase 新增至 C++ 專案時,您需要在Firebase控制台和開啟的 C++ 專案中執行工作 (例如從控制台下載 Firebase 設定檔,然後移至 C++ 專案)。
步驟 2:在應用程式中加入 Remote Config
將 Firebase 新增至應用程式後:
建立 Firebase 應用程式,並傳遞 JNI 環境和活動:
app = ::firebase::App::Create(::firebase::AppOptions(), jni_env, activity);
如以下範例所示,初始化 Remote Config 程式庫:
::firebase::remote_config::Initialize(app);
將 Firebase 新增至應用程式後:
建立 Firebase 應用程式:
app = ::firebase::App::Create(::firebase::AppOptions());
如以下範例所示,初始化 Remote Config 程式庫:
::firebase::remote_config::Initialize(app);
步驟 3:設定應用程式內預設參數值
您可以在 Remote Config 物件中設定應用程式的預設參數值,讓應用程式在連線至 Remote Config 後端前正常運作,並在後端未設定任何值時提供預設值。
使用
ConfigKeyValue*
物件或ConfigKeyValueVariant*
物件 (陣列大小) 定義一組參數名稱和預設參數值。如果您已設定 Remote Config 後端參數值,可以下載包含這些鍵/值組合的檔案,並用來建構
map
物件。詳情請參閱「下載範本預設值」。Remote Config使用
SetDefaults()
將這些值新增至 Remote Config 物件。
步驟 4:取得要在應用程式中使用的參數值
現在您可以從 Remote Config 物件取得參數值。如果您在 Remote Config 後端設定值、擷取這些值,然後啟用這些值,應用程式就能使用這些值。否則,您會取得使用 SetDefaults()
設定的應用程式內參數值。
如要取得這些值,請呼叫下列對應至應用程式預期資料類型的方法,並提供參數鍵做為引數:
步驟 5:設定參數值
- 在 Firebase 控制台中開啟專案。
- 選取選單中的 Remote Config,即可查看 Remote Config 資訊主頁。
- 定義的參數名稱必須與應用程式中定義的參數名稱相同。您可以為每個參數設定預設值 (最終會覆寫應用程式中的預設值) 和條件值。詳情請參閱Remote Config參數和條件。
步驟 6:擷取並啟用值
- 如要從 Remote Config 後端擷取參數值,請呼叫
Fetch()
方法。系統會擷取您在後端設定的所有值,並快取在 Remote Config 物件中。 - 如要讓應用程式使用擷取的參數值,請呼叫
ActivateFetched()
。
步驟 7:即時收聽最新消息
擷取參數值後,您可以使用即時 Remote Config 監聽 Remote Config 後端的更新。有更新時,系統會向連線裝置傳送即時Remote Config信號,並在您發布新Remote Config版本後自動擷取變更。
Firebase C++ SDK 11.0.0 以上版本支援 Android 和 Apple 平台即時更新。
- 在應用程式中呼叫
AddOnConfigUpdateListener
,開始監聽更新,並自動擷取任何新的或更新的參數值。下列範例會監聽更新,並在呼叫Activate
時,使用新擷取的值顯示更新的歡迎訊息。
remote_config->AddOnConfigUpdateListener( [](firebase::remote_config::ConfigUpdate&& config_update, firebase::remote_config::RemoteConfigError remote_config_error) { if (remote_config_error != firebase::remote_config::kRemoteConfigErrorNone) { printf("Error listening for config updates: %d", remote_config_error); } // Search the `updated_keys` set for the key "welcome_message." // `updated_keys` represents the keys that have changed since the last // fetch. if (std::find(config_update.updated_keys.begin(), config_update.updated_keys.end(), "welcome_message") != config_update.updated_keys.end()) { remote_config->Activate().OnCompletion( [&](const firebase::Future& completed_future, void* user_data) { // The key "welcome_message" was found within `updated_keys` and // can be activated. if (completed_future.error() == 0) { DisplayWelcomeMessage(); } else { printf("Error activating config: %d", completed_future.error()); } }, nullptr); } });
下次發布新版 Remote Config 時,執行應用程式並監聽變更的裝置會呼叫設定更新監聽器。
後續步驟
如果您尚未探索Remote Config 應用情境,請參閱一些重要概念和進階策略說明文件,包括: