停用 Firebase Performance Monitoring

在应用开发和测试期间,您可能发现停用 Performance Monitoring 会很有用。

例如,通过在应用构建过程中停用 Performance Monitoring,您可以:

  • 在调试 build 中停用 Performance Monitoring 的某些功能(例如,Performance Monitoring Gradle 插件提供的功能),但为发布 build 重新启用这些功能。

  • 在构建应用时停用 Performance Monitoring,但允许应用在运行时重新启用它。

  • 在构建应用时停用 Performance Monitoring,且不允许应用在运行时重新启用它。

您还可以在构建应用时启用 Performance Monitoring,但使用 Firebase Remote Config 灵活地在生产应用中停用(和重新启用)Performance Monitoring。通过此选项,您甚至可以将应用配置为允许用户选择启用或选择停用 Performance Monitoring。

在应用构建过程中停用 Performance Monitoring

通过停用 Performance Monitoring Gradle 插件和/或停用 Performance Monitoring Android 库,您可以在构建过程中停用 Performance Monitoring。

在开发和调试期间,停用插件会很有用,因为插件所执行的插桩可能会延长构建时间。但您也许应考虑启用库,以便您仍然可以在应用中查看应用启动、应用前台活动和应用后台活动跟踪记录以及任何自定义代码跟踪记录中的性能数据。

停用 Performance Monitoring Gradle 插件

您可以使用以下选项添加 instrumentationEnabled 标志,从而停用 Performance Monitoring 插件:

通过 Extension Property 标志停用插件

通过使用 Extensions Property 标志,您可以在编译时为特定 build 变体停用 Performance Moinitoring 插件。

  1. 根级(项目级)Gradle 文件(<project>/build.gradle.kts<project>/build.gradle)中,确保将 Android Gradle 插件依赖项指定为 v3.4.0 或更高版本。

    对于早期版本的 Android Gradle 插件,您仍然可以为特定 build 变体停用 Performance Monitoring 插件,但无法为该变体完全消除增加的构建时间。

  2. 将以下标志添加到您的模块(应用级)Gradle 文件(通常为 <project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle),然后将其设置为 false 以停用 Performance Monitoring 插件。

    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
          }
        }
      }
    }
    

通过 Project Property 标志停用插件

通过使用 Project Property 标志,您可以在编译时为所有 build 变体停用 Performance Monitoring 插件。

将以下标志添加到您的 gradle.properties 文件,然后将其设置为 false 以停用 Performance Monitoring 插件。

// ...

// 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

停用 Performance Monitoring Android 库

如果您在编译时停用 Performance Monitoring 库,则可以选择是否允许您的应用在运行时启用该库。

在编译时停用库,但允许应用在运行时启用它

将以下 <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>

使用 Remote Config 在运行时停用您的应用

您可以使用 Firebase Remote Config 更改应用的行为和外观,因此,如需为您的应用的已部署实例停用 Performance Monitoring,利用 Remote Config 是一种理想的方式。

如需在 Android 应用下次启动时停用 Performance Monitoring 数据收集,请使用下面的示例代码。如需详细了解如何在 Android 应用中使用 Remote Config,请参阅使用 Firebase Remote Config(Android 版)

  1. 确保 Remote Config 位于您的模块(应用级)Gradle 文件(通常是 <project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle)的 dependencies 部分中:

    Kotlin+KTX

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

    Java

      implementation("com.google.firebase:firebase-config:21.6.3")
    
  2. 设置 Remote Config,并停用 Performance Monitoring(如果 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 以提取并激活 Remote Config 值:

    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 控制台中停用 Performance Monitoring,请在应用的项目中创建一个 perf_disable 参数,然后将其值设置为 true

    进行此更改后,Performance Monitoring SDK 调用将变为“无操作”调用 (NOOPs),如此消除了在应用中使用 Performance Monitoring SDK 而对应用性能造成的显著影响。

    如果将 perf_disable 的值设置为 false,则 Performance Monitoring 将保持启用状态。