禁用 Firebase 效能監控

在應用程式開發和測試期間,您可能會發現停用效能監控很有用。

例如,透過在應用程式建置過程中停用效能監控,您可以:

  • 在偵錯版本中停用效能監控的某些功能(例如效能監控 Gradle 外掛程式提供的功能),但為發布版本重新啟用這些功能。

  • 建立應用程式時會停用效能監控,但允許應用程式在運行時重新啟用它。

  • 建立應用程式時會停用效能監控,並且不允許您的應用程式在運行時重新啟用它。

您也可以在啟用效能監控的情況下建立應用程序,但使用 Firebase 遠端配置可讓您靈活地在生產應用程式中停用(和重新啟用)效能監控。使用此選項,您甚至可以配置應用程式以允許使用者選擇加入或選擇退出使用效能監控。

在應用程式建置過程中停用效能監控

您可以在建置過程中透過停用效能監控 Gradle 外掛程式和/或停用效能監控 Android 程式庫來停用效能監控。

在開發和調試期間,停用插件非常有用,因為插件的檢測可能會增加建置時間。不過,您可能會考慮保持該庫處於啟用狀態,以便您仍然可以查看應用程式啟動、應用程式在前台和應用程式在後台追蹤以及應用程式中的任何自訂程式碼追蹤的效能資料。

禁用性能監控 Gradle 插件

您可以透過使用以下選項新增instrumentationEnabled標誌來停用效能監控外掛程式:

透過擴充屬性標誌禁用插件

透過使用擴充屬性標誌,您可以在編譯時停用特定建置變體的效能監控插件。

  1. 根級(專案級) Gradle 檔案( <project>/build.gradle.kts<project>/build.gradle )中,請確保您的 Android Gradle 外掛程式依賴項指定為 v3.4.0 或更高版本。

    對於早期版本的 Android Gradle 插件,您仍然可以停用特定建置變體的效能監控插件,但該變體的建置時間貢獻不會完全消除。

  2. 將以下標誌加入模組(應用程式層級) Gradle 檔案(通常<project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle ),然後設定它設定為false以停用效能監控插件。

    Kotlin

    import com.google.firebase.perf.plugin.FirebasePerfExtension
    
    // ...
    
    android {
      // ...
      buildTypes {
        getByName("debug") {
          configure<FirebasePerfExtension> {
            // Set this flag to 'false' to disable @AddTrace annotation processing and
            // automatic monitoring of HTTP/S network requests
            // for a specific build variant at compile time.
            setInstrumentationEnabled(false)
          }
        }
      }
    }
    

    Groovy

    android {
      // ...
      buildTypes {
        debug {
          FirebasePerformance {
            // Set this flag to 'false' to disable @AddTrace annotation processing and
            // automatic monitoring of HTTP/S network requests
            // for a specific build variant at compile time.
            instrumentationEnabled false
          }
        }
      }
    }
    

透過項目屬性標誌禁用插件

透過使用專案屬性標誌,您可以在編譯時停用所有建置變體的效能監控插件。

將以下標誌新增至gradle.properties檔案中,然後將其設為false以停用效能監控插件。

// ...

// Set this flag to 'false' to disable @AddTrace annotation processing and
// automatic monitoring of HTTP/S network requests
// for all build variants at compile time.
firebasePerformanceInstrumentationEnabled=false

停用效能監控 Android 函式庫

如果您在編譯時停用效能監控庫,您可以選擇是否允許您的應用程式在執行時啟用該程式庫。

在編譯時禁用該庫,但允許您的應用程式在運行時啟用它

將以下<meta-data>元素加入到應用的AndroidManifest.xml檔案中:

  <application>
    <meta-data
      android:name="firebase_performance_collection_enabled"
      android:value="false" />
  </application>

在編譯時禁用該庫,但不允許您的應用程式在運行時啟用它

將以下<meta-data>元素加入到應用的AndroidManifest.xml檔案中:

  <application>
    <meta-data
      android:name="firebase_performance_collection_deactivated"
      android:value="true" />
  </application>

使用遠端配置在運行時停用您的應用程式

Firebase 遠端配置可讓您變更應用程式的行為和外觀,因此它提供了一種理想的方法來讓您在應用程式的已部署實例中停用效能監控。

若要在 Android 應用程式下次啟動時停用效能監控資料收集,請使用下面所示的範例程式碼。有關在 Android 應用中使用遠端配置的更多信息,請參閱在 Android 上使用 Firebase 遠端配置

  1. 確保遠端配置位於模組(應用程式層級) Gradle 檔案的dependencies部分(通常<project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle ):

    Kotlin+KTX

      implementation("com.google.firebase:firebase-config-ktx:21.6.3")
    

    Java

      implementation("com.google.firebase:firebase-config:21.6.3")
    
  2. 如果perf_disable設定為true ,則設定遠端配置並停用效能監控:

    Kotlin+KTX

    // Setup remote config
    val config = Firebase.remoteConfig
    
    // You can uncomment the following two statements to permit more fetches when
    // validating your app, but you should comment out or delete these lines before
    // distributing your app in production.
    // val configSettings = remoteConfigSettings {
    //     minimumFetchIntervalInSeconds = 3600
    // }
    // config.setConfigSettingsAsync(configSettings)
    // Load in-app defaults from an XML file that sets perf_disable to false until you update
    // values in the Firebase Console
    
    // Observe the remote config parameter "perf_disable" and disable Performance Monitoring if true
    config.setDefaultsAsync(R.xml.remote_config_defaults)
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                Firebase.performance.isPerformanceCollectionEnabled = !config.getBoolean("perf_disable")
            } else {
                // An error occurred while setting default parameters
            }
        }

    Java

    // Setup remote config
    final FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();
    
    // You can uncomment the following two statements to permit more fetches when
    // validating your app, but you should comment out or delete these lines before
    // distributing your app in production.
    // FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
    //       .setMinimumFetchIntervalInSeconds(3600)
    //       .build();
    // config.setConfigSettingsAsync(configSettings);
    // Load in-app defaults from an XML file that sets perf_disable to false until you update
    // values in the Firebase Console
    
    //Observe the remote config parameter "perf_disable" and disable Performance Monitoring if true
    config.setDefaultsAsync(R.xml.remote_config_defaults)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        if (config.getBoolean("perf_disable")) {
                            FirebasePerformance.getInstance().setPerformanceCollectionEnabled(false);
                        } else {
                            FirebasePerformance.getInstance().setPerformanceCollectionEnabled(true);
                        }
                    } else {
                        // An error occurred while setting default parameters
                    }
                }
            });
  3. 將以下程式碼新增至MainActivity.java以取得並啟動遠端配置值:

    Kotlin+KTX

    // Remote Config fetches and activates parameter values from the service
    val config = Firebase.remoteConfig
    config.fetch(3600)
        .continueWithTask { task ->
            if (!task.isSuccessful) {
                task.exception?.let {
                    throw it
                }
            }
            config.activate()
        }
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                // Parameter values successfully activated
                // ...
            } else {
                // Handle errors
            }
        }

    Java

    //Remote Config fetches and activates parameter values from the service
    final FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();
    config.fetch(3600)
            .continueWithTask(new Continuation<Void, Task<Boolean>>() {
                @Override
                public Task<Boolean> then(@NonNull Task<Void> task) throws Exception {
                    if (!task.isSuccessful()) {
                        throw task.getException();
                    }
                    return config.activate();
                }
            })
            .addOnCompleteListener(new OnCompleteListener<Boolean>() {
                @Override
                public void onComplete(@NonNull Task<Boolean> task) {
                    if (task.isSuccessful()) {
                        // Parameter values successfully activated
                        // ...
                    } else {
                        // Handle errors
                    }
                }
            });
  4. 若要在 Firebase 控制台中停用效能監控,請在套用的專案中建立一個perf_disable參數,然後將其值設為true

    此變更將呼叫效能監控 SDK「無操作」呼叫 (NOOP),從而消除在應用程式中使用效能監控 SDK 對應用程式效能的任何重大影響。

    如果將perf_disable的值設為false ,效能監控將保持啟用狀態。