禁用 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.4.1")
    

    Java

      implementation("com.google.firebase:firebase-config:21.4.1")
    
  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 ,性能監控將保持啟用狀態。