---
metadata:
  - name: generator
    content: Diplodoc Platform v5.63.4
alternate:
  - https://appmetrica.yandex.com/docs/en/sdk/android/push/quick-start.md
  - https://appmetrica.yandex.com/docs/ru/sdk/android/push/quick-start.md
  - https://appmetrica.yandex.com/docs/zh/sdk/android/push/quick-start.md
  - href: https://appmetrica.yandex.com/docs/zh/sdk/android/push/quick-start.md
    type: text/markdown
    title: Markdown version
  - href: https://appmetrica.yandex.com/docs/zh/llms.txt?revision=r21698989
    rel: describedby
---
> **Documentation Index:** Fetch the complete configuration index at https://appmetrica.yandex.com/docs/zh/llms.txt?revision=r21698989

# 安装和初始化

Android 推送 SDK 是一个 AAR 格式的库。
该库可在 [Maven 仓库](https://search.maven.org/search?q=g:io.appmetrica.analytics%20AND%20a:push) 中获取。

此部分介绍启用和初始化 AppMetrica Push SDK 的步骤：

## 步骤 1.  准备您的应用 {#preparation}

在集成 AppMetrica Push SDK 库之前，请先准备您的应用：

1. [集成AppMetricaSDK 库，版本至少为 6.0.0](https://appmetrica.yandex.com/docs/zh/sdk/android/analytics/quick-start.md)
2. [配置您的应用](https://appmetrica.yandex.com/docs/zh/sdk/android/push/android-settings.md)以发送推送通知。

## 步骤 2. 启用库 {#installation}

Push SDK 使用 [OKHttp](https://github.com/square/okhttp) 库来缓存推送通知中显示的图片。
缓存规则从 `cache-control` HTTP 头获取。
如果不想缓存图片，请连接不带缓存的库。

1. 如果你使用 Gradle 构建应用，请在应用的 Gradle 文件中添加依赖：

   {% cut "带缓存" %}

     {% list tabs %}

     - build.gradle.kts

       ```kotlin translate=no
       dependencies {
           // AppMetrica Push SDK.
           implementation("io.appmetrica.analytics:push:4.3.0")
           implementation("androidx.legacy:legacy-support-v4:1.0.0")
       }
       ```

     - build.gradle

       ```groovy translate=no
       dependencies {
           // AppMetrica Push SDK.
           implementation "io.appmetrica.analytics:push:4.3.0"
           implementation "androidx.legacy:legacy-support-v4:1.0.0"
       }
       ```

     {% endlist %}

   {% endcut %}

   {% cut "不带缓存" %}

     {% list tabs %}

     - build.gradle.kts

       ```kotlin translate=no
       dependencies {
           // AppMetrica Push SDK.
           implementation("io.appmetrica.analytics:push:4.3.0") {
             exclude(group = "com.squareup.okhttp3", module = "okhttp")
           }
           implementation("androidx.legacy:legacy-support-v4:1.0.0")
       }
       ```

     - build.gradle

       ```groovy translate=no
       dependencies {
           // AppMetrica Push SDK.
           implementation "io.appmetrica.analytics:push:4.3.0" {
            exclude group: "com.squareup.okhttp3", module: "okhttp"
           }
           implementation "androidx.legacy:legacy-support-v4:1.0.0"
       }
       ```

     {% endlist %}

   {% endcut %}

1. 连接运输。

   {% list tabs %}

   - Firebase

     1. 如果你使用 Gradle 构建应用，请将依赖项添加到应用的 Gradle 文件中：

        - **应用/build.gradle.kts**

          ```kotlin translate=no
          dependencies {
                  // minimum support version 20.3.0
                  implementation("com.google.firebase:firebase-messaging:22.0.0")
                  implementation("com.google.android.gms:play-services-base:17.5.0")
              }
          ```

        - **app/build.gradle**

          ```groovy translate=no
          dependencies {
                  // minimum support version 20.3.0
                  implementation "com.google.firebase:firebase-messaging:22.0.0"
                  implementation "com.google.android.gms:play-services-base:17.5.0"
              }
          ```
        开发中使用的版本列在 [仓库](https://github.com/appmetrica/push-sdk-android/blob/main/build-logic/src/main/kotlin/io/appmetrica/analytics/gradle/PushConstants.kt#L30) 中。

     1. 使用以下方法之一初始化 Firebase：

        {% cut "使用 Google Services 插件" %}

        1. [下载](https://support.google.com/firebase/answer/7015592)配置文件`google-services.json`，并将其放置在项目模块目录中（例如`app`）。
        1. 为了文件正常工作，请在项目中启用 Google Services 插件，将以下行添加到 Gradle 文件中：

            **项目**

           - **build.gradle.kts**

             ```kotlin translate=no
             buildscript {
                 dependencies {
                     classpath("com.google.gms:google-services:4.4.0")
                 }
             }
             ```
           - **build.gradle**

             ```groovy translate=no
             buildscript {
                 dependencies {
                     classpath "com.google.gms:google-services:4.4.0"
                 }
             }
             ```

            **应用程序（模块）**

            - **应用/build.gradle.kts**

              ```kotlin translate=no
              apply(plugin = "com.google.gms.google-services")
              ```
            - **app/build.gradle**

              ```groovy translate=no
              apply plugin: "com.google.gms.google-services"
              ```

        {% endcut %}

        {% cut "不使用插件" %}

        在 `应用` 元素中修改 `AndroidManifest.xml` 文件：

        ```xml translate=no
        <meta-data android:name="ymp_firebase_default_app_id" android:value="APP_ID"/>
        <meta-data android:name="ymp_gcm_default_sender_id" android:value="number:SENDER_ID"/>
        <meta-data android:name="ymp_firebase_default_api_key" android:value="API_KEY"/>
        <meta-data android:name="ymp_firebase_default_project_id" android:value="PROJECT_ID"/>
        ```

        `APP_ID` — 应用在 Firebase 中的 ID。 您可以在 [Firebase 控制台](https://console.firebase.google.com/) 中找到它：转到 **项目设置**。 在 **您的应用** 部分，复制 **应用 ID** 字段的值。


        `SENDER_ID` — Firebase 中发送者的唯一 ID。 您可以在 [Firebase 控制台](https://console.firebase.google.com/) 中找到它：转到 **项目设置**&nbsp;→ **云消息传递**，并复制 **发送者 ID** 字段的值。


        `API_KEY` — Firebase 中的应用密钥。 您可以在 `google-services.json` 文件的 `current_key` 字段中找到它。 您可以在 [Firebase 控制台](https://support.google.com/firebase/answer/7015592) 中下载该文件。


        `PROJECT_ID` — Firebase 中的应用 ID。 您可以在 `google-services.json` 文件的 `project_id` 字段中找到它。 您可以在 [Firebase 控制台](https://console.firebase.google.com/) 中下载该文件。


        {% endcut %}

        {% cut "使用其他 Firebase 项目" %}

        在 `应用` 元素中修改 `AndroidManifest.xml` 文件：

        ```xml translate=no
        <meta-data android:name="ymp_firebase_app_id" android:value="APP_ID"/>
        <meta-data android:name="ymp_gcm_sender_id" android:value="number:SENDER_ID"/>
        <meta-data android:name="ymp_firebase_api_key" android:value="API_KEY"/>
        <meta-data android:name="ymp_firebase_project_id" android:value="PROJECT_ID"/>
        ```

        `APP_ID` — 应用在 Firebase 中的 ID。 您可以在 [Firebase 控制台](https://console.firebase.google.com/) 中找到它：转到 **项目设置**。 在 **您的应用** 部分，复制 **应用 ID** 字段的值。


        `SENDER_ID` — Firebase 中发送者的唯一 ID。 您可以在 [Firebase 控制台](https://console.firebase.google.com/) 中找到它：转到 **项目设置**&nbsp;→ **云消息传递**，并复制 **发送者 ID** 字段的值。


        `API_KEY` — Firebase 中的应用密钥。 您可以在 `google-services.json` 文件的 `current_key` 字段中找到它。 您可以在 [Firebase 控制台](https://support.google.com/firebase/answer/7015592) 中下载该文件。


        `PROJECT_ID` — Firebase 中的应用 ID。 您可以在 `google-services.json` 文件的 `project_id` 字段中找到它。 您可以在 [Firebase 控制台](https://console.firebase.google.com/) 中下载该文件。


        {% note alert %}

        您需要初始化默认的Firebase项目。

        {% endnote %}

        {% endcut %}

   - HMS

     1. 向项目添加[HMS Push Kit](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-app-quickstart-0000001071490422)。 开发中使用的版本列于[仓库](https://github.com/appmetrica/push-sdk-android/blob/main/build-logic/src/main/kotlin/io/appmetrica/analytics/gradle/PushConstants.kt#L33)中。
     1. 如果你使用 Gradle 构建应用，请将依赖项添加到应用的 Gradle 文件中：

        - **应用/build.gradle.kts**
          ```kotlin translate=no
          dependencies {
              implementation("io.appmetrica.analytics:push-provider-hms:4.3.0")
          }
          ```

        - **app/build.gradle**
          ```groovy translate=no
          dependencies {
              implementation "io.appmetrica.analytics:push-provider-hms:4.3.0"
          }
          ```

        {% note alert %}

        如果你只使用 HMS，请从主库中排除 Firebase 依赖：

         - **应用/build.gradle.kts**
           ```kotlin translate=no
           dependencies {
               implementation("io.appmetrica.analytics:push:4.3.0") {
                   exclude(group =  "io.appmetrica.analytics", module = "push-provider-firebase")
               }
           }
           ```

         - **app/build.gradle**
           ```groovy translate=no
           dependencies {
               implementation("io.appmetrica.analytics:push:4.3.0") {
                   exclude group: "io.appmetrica.analytics", module: "push-provider-firebase"
               }
           }
           ```

        {% endnote %}

     1. 在 `应用` 元素中修改 `AndroidManifest.xml` 文件：

        ```xml translate=no
        <meta-data android:name="ymp_hms_default_app_id" android:value="number:APP_ID"/>
        ```

        `APP_ID` — HMS 中的应用 ID。 你可以在 `app_id` 字段的 `agconnect-services.json` 文件中找到它。 文件可以从[华为控制台](https://developer.huawei.com/consumer/zh/service/josp/agc/index.html)下载。

   {% endlist %}

推送 SDK AppMetrica 可以同时与 Firebase 和 HMS 共同工作。

## 步骤 3. 初始化库 {#initialization}

在应用程序中初始化库——扩展`Application`类，并覆盖`onCreate()`方法，如下所示：

{% cut "Firebase 仅" %}

{% list tabs group=instructions %}

- Kotlin

  ```kotlin translate=no
  class MyApp : Application() {
      override fun onCreate() {
          super.onCreate()
          AppMetricaPush.activate(applicationContext)
      }
  }
  ```

- Java

  ```java translate=no
  public class MyApp extends Application {
      @Override
      public void onCreate() {
          super.onCreate();
          AppMetricaPush.activate(getApplicationContext());
      }
  }
  ```

{% endlist %}

{% endcut %}

{% cut "HMS 仅" %}

{% list tabs group=instructions %}

- Kotlin

  ```kotlin translate=no
  class MyApp : Application() {
      override fun onCreate() {
          super.onCreate()
          AppMetricaPush.activate(applicationContext, HmsPushServiceControllerProvider(this))
      }
  }
  ```

- Java

  ```java translate=no
  public class MyApp extends Application {
      @Override
      public void onCreate() {
          super.onCreate();
          AppMetricaPush.activate(getApplicationContext(), new HmsPushServiceControllerProvider(this));
      }
  }
  ```

{% endlist %}

{% endcut %}

{% cut "Firebase 和 HMS" %}

{% list tabs group=instructions %}

- Kotlin

  添加以下依赖以允许调用`FirebasePushServiceControllerProvider(this)`：

  ```kotlin translate=no
  dependencies {
      implementation("io.appmetrica.analytics:push-provider-firebase:$appmetrica_push_version")
  }
  ```

  覆盖类：

  ```kotlin translate=no
  class MyApp : Application() {
      override fun onCreate() {
          super.onCreate()
          AppMetricaPush.activate(
              applicationContext,
              FirebasePushServiceControllerProvider(this),
              HmsPushServiceControllerProvider(this)
          )
      }
  }
  ```

- Java

  添加以下依赖以允许调用`FirebasePushServiceControllerProvider(this)`：

  ```java translate=no
  dependencies {
      implementation "io.appmetrica.analytics:push-provider-firebase:$appmetrica_push_version"
  }
  ```

  覆盖类：

  ```java translate=no
  public class MyApp extends Application {
      @Override
      public void onCreate() {
          super.onCreate();
          AppMetricaPush.activate(
              getApplicationContext(),
              new FirebasePushServiceControllerProvider(this),
              new HmsPushServiceControllerProvider(this)
          );
      }
  }
  ```

{% endlist %}

{% endcut %}

{% note alert %}

必须在主进程中初始化 AppMetrica Push SDK 库。

{% endnote %}

## 第 4 步。 (_可选_) 配置静默推送通知 {#settings-of-silent-push}

配置处理静默推送通知。

1. 创建一个特殊的 `BroadcastReceiver`：

   {% list tabs group=instructions %}

    - Kotlin

      ```kotlin translate=no
      class SilentPushReceiver : BroadcastReceiver() {
          override fun onReceive(context: Context, intent: Intent) {
              // Extract push message payload from your push message.
              val payload = intent.getStringExtra(AppMetricaPush.EXTRA_PAYLOAD)
          }
      }
      ```

   - Java

     ```java translate=no
     public class SilentPushReceiver extends BroadcastReceiver {
         @Override
         public void onReceive(Context context, Intent intent) {
             // Extract push message payload from your push message.
             String payload = intent.getStringExtra(AppMetricaPush.EXTRA_PAYLOAD);
         }
     }
     ```

   {% endlist %}

2. 在 `应用` 元素中修改 `AndroidManifest.xml` 文件：

    ```xml translate=no
    <manifest xmlns:android="http://schemas.android.com/apk/res/android">
      <application>
        <receiver android:name=".SilentPushReceiver">
          <intent-filter>
            <!-- Receive silent push notifications -->
            <action android:name="${applicationId}.action.ymp.SILENT_PUSH_RECEIVE"/>
          </intent-filter>
        </receiver>
      </application>
    </manifest>
    ```

    `applicationId` — Gradle 中唯一的应用 ID（包名）。
    例如，`com.example.name`.

## 第 5 步。 (_可选_) 启用推送令牌更新 {#actualization}

{% note alert "" %}

如果您有自己的服务来处理推送通知（继承自`FirebaseMessagingService` 或 `HmsMessageService` 的类），请检查您是否没有处理来自 AppMetrica 的推送通知。

要检查推送通知不是来自 AppMetrica，请使用 `AppMetricaMessagingService.isNotificationRelatedToSDK` 或 `AppMetricaHmsMessagingService.isNotificationRelatedToSDK` 方法。

{% endnote %}

FCM 服务可能会撤回设备的推送令牌，例如当用户长时间未启动应用时。 AppMetrica 在服务器上存储推送令牌，无法向具有过时令牌的设备发送推送通知。

要自动收集当前的 push token，请在 AppMetrica 界面中进入应用设置，并启用 **使用静默推送更新令牌** 选项，在 **推送通知** 选项卡中。

## 第6步。 (_可选_) 配置与其他推送 SDK 的使用 {#other-push-services}

如果您已将多个SDK集成到应用中以处理推送通知，请参考指南[与其他推送服务配合使用](https://appmetrica.yandex.com/docs/zh/sdk/android/push/android-other-push-services-settings.md)。

{% note info "" %}

需要进行额外的设置，否则可能会出现处理推送通知的问题。

{% endnote %}

## 发送额外信息 {#send-additional-info}

如果需要，您可以随推送通知一起发送额外信息。 这些数据在AppMetrica网页界面中[配置推送活动](https://appmetrica.yandex.com/docs/zh/push/marketing.md)时指定。

{% list tabs group=instructions %}

- Kotlin

  ```kotlin translate=no
  class TargetActivity : Activity() {
      override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          handlePayload(intent)
      }

      override fun onNewIntent(intent: Intent) {
          super.onNewIntent(intent)
          handlePayload(intent)
      }

      private fun handlePayload(intent: Intent) {
          // Handle your payload.
          val payload = intent.getStringExtra(AppMetricaPush.EXTRA_PAYLOAD)
      }
  }
  ```

- Java

  ```java translate=no
  public class TargetActivity extends Activity {
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          handlePayload(getIntent());
      }

      @Override
      protected void onNewIntent(Intent intent) {
          super.onNewIntent(intent);
          handlePayload(intent);
      }

      private void handlePayload(Intent intent) {
          // Handle your payload.
          String payload = intent.getStringExtra(AppMetricaPush.EXTRA_PAYLOAD);
      }
  }
  ```

{% endlist %}

## 通过推送通知检测应用启动 {#track-start-via-push}

要区分通过打开AppMetrica推送通知启动应用和应用总启动次数，您需要检查应用的[Intent action](https://developer.android.com/reference/android/content/Intent.html#getAction())：

- 如果您将深链路指定为操作，这将是 Intent 操作。

- 如果将操作设置为打开应用，Intent 操作会传递值`AppMetricaPush#OPEN_DEFAULT_ACTIVITY_ACTION`.

## 设置默认图标 {#icon}

要设置默认的推送通知图标，请在 `应用` 元素中修改 `AndroidManifest.xml` 文件：

```
<meta-data android:name="io.appmetrica.analytics.push.default_notification_icon"
           android:resource="ICON_RESOURCE"/>
```

`ICON_RESOURCE` — 图标资源。
例如，`@drawable/large_icon`.

## 修改通知通道设置 {#notification-channel}

您可以修改默认通知通道的设置。 例如，为它添加描述或修改其优先级。

{% note info "" %}

您只能在通道创建之前更改通道设置，也就是在通过 AppMetrica 发送首次推送之前。

{% endnote %}

要获取默认通道，调用 `getDefaultNotificationChannel()` 方法：

{% list tabs group=instructions %}

- Kotlin

  ```kotlin translate=no
  AppMetricaPush.getDefaultNotificationChannel()?.apply {
      description = "Push from AppMetrica"
      importance = NotificationManager.IMPORTANCE_HIGH
      // Modify NotificationChannel properties
  }
  ```

- Java

  ```java translate=no
  NotificationChannel channel = AppMetricaPush.getDefaultNotificationChannel();
  if (channel != null) {
      channel.setDescription("Push from AppMetrica");
      channel.setImportance(NotificationManager.IMPORTANCE_HIGH);
      // Modify NotificationChannel
  }
  ```

{% endlist %}

## 了解更多 {#learn-more}

- [配置 Android 应用以发送推送通知](https://appmetrica.yandex.com/docs/zh/sdk/android/push/android-settings.md)
- [如何确保已安装最新版本的Android库？](https://appmetrica.yandex.com/docs/zh/troubleshooting/troubleshooting.md#newest-android-version)

<!-- source: zh/_includes/feedback-button-3.md -->
如果您没有找到所需答案，可以通过反馈表单提交您的问题。 请尽可能详细地描述问题。 如果可能，请附上截图。

<a href="../troubleshooting/feedback-new">
  <span class="button">联系支持</span>
</a>

<a href="../troubleshooting/feedback-docs">
  <span class="button">为文档提出改进建议</span>
</a>
<!-- endsource: zh/_includes/feedback-button-3.md -->
