Installation and initialization

The Push SDK for Android is a library in the AAR format. The library is available in the Maven repository.

This section describes the steps to enable and initialize AppMetrica Push SDK:

Step 1. Prepare your app

Before integrating the AppMetrica Push SDK library, prepare your app:

  1. Integrate the AppMetrica SDK library at least version 6.0.0.
  2. Configure your app for sending push notifications.

Step 2. Enable the library

Push SDK uses the OKHttp library to cache images displayed in push notifications. Caching rules are taken from the cache-control HTTP header. If you do not want the images to be cached, connect the library without caching.

  1. If you use Gradle to build the app, add the dependency to the app's Gradle file:

    With caching
    dependencies {
        // AppMetrica Push SDK.
        implementation("io.appmetrica.analytics:push:4.0.0")
        implementation("androidx.legacy:legacy-support-v4:1.0.0")
    }
    
    dependencies {
        // AppMetrica Push SDK.
        implementation "io.appmetrica.analytics:push:4.0.0"
        implementation "androidx.legacy:legacy-support-v4:1.0.0"
    }
    
    Without caching
    dependencies {
        // AppMetrica Push SDK.
        implementation("io.appmetrica.analytics:push:4.0.0") {
          exclude(group = "com.squareup.okhttp3", module = "okhttp")
        }
        implementation("androidx.legacy:legacy-support-v4:1.0.0")
    }
    
    dependencies {
        // AppMetrica Push SDK.
        implementation "io.appmetrica.analytics:push:4.0.0" {
         exclude group: "com.squareup.okhttp3", module: "okhttp"
        }
        implementation "androidx.legacy:legacy-support-v4:1.0.0"
    }
    
  2. Connect the transport.

    1. If you use Gradle to build the app, add the dependency to the app's Gradle file:

      • app/build.gradle.kts

        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

        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"
            }
        
    2. Initialize Firebase using one of the following methods:

      Using Google Services Plugin
      1. Download the configuration file google-services.json and put it in the project module's directory (such as app).

      2. For the file to work correctly, enable the Google Services plugin in the project by adding the following lines to the Gradle file:

        project

        • build.gradle.kts

          buildscript {
              dependencies {
                  classpath("com.google.gms:google-services:4.4.0")
              }
          }
          
        • build.gradle

          buildscript {
              dependencies {
                  classpath "com.google.gms:google-services:4.4.0"
              }
          }
          

        application (module)

        • app/build.gradle.kts

          apply(plugin = "com.google.gms.google-services")
          
        • app/build.gradle

          apply plugin: "com.google.gms.google-services"
          
      Without using the plugin

      Make changes in the application element in the AndroidManifest.xml file:

      <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 — ID of the app in Firebase. You can find it in the Firebase console: go to the Project settings. In the Your application section copy the value of the application ID field.

      SENDER_ID — The unique ID of sender in Firebase. You can find it in the Firebase console: go to Project settings → Cloud Messaging and copy the value of the Sender ID field.

      API_KEY — App key in Firebase. You can find it in the current_key field of the google-services.json file. You can download the file in the Firebase console.

      PROJECT_ID — App ID in Firebase. You can find it in the project_id field of the google-services.json file. You can download the file in the Firebase console.

      Using with other Firebase projects

      Make changes in the application element in the AndroidManifest.xml file:

      <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 — ID of the app in Firebase. You can find it in the Firebase console: go to the Project settings. In the Your application section copy the value of the application ID field.

      SENDER_ID — The unique ID of sender in Firebase. You can find it in the Firebase console: go to Project settings → Cloud Messaging and copy the value of the Sender ID field.

      API_KEY — App key in Firebase. You can find it in the current_key field of the google-services.json file. You can download the file in the Firebase console.

      PROJECT_ID — App ID in Firebase. You can find it in the project_id field of the google-services.json file. You can download the file in the Firebase console.

      Alert

      You should initialize default Firebase project.

    1. Add HMS Push Kit to the project.

    2. If you use Gradle to build the app, add the dependency to the app's Gradle file:

      • app/build.gradle.kts

        dependencies {
            implementation("io.appmetrica.analytics:push-provider-hms:4.0.0")
        }
        
      • app/build.gradle

        dependencies {
            implementation "io.appmetrica.analytics:push-provider-hms:4.0.0"
        }
        

      Alert

      If you're only going to use HMS, exclude the Firebase dependency from the main library:

      • app/build.gradle.kts

        dependencies {
            implementation("io.appmetrica.analytics:push:4.0.0") {
                exclude(group =  "io.appmetrica.analytics", module = "push-provider-firebase")
            }
        }
        
      • app/build.gradle

        dependencies {
            implementation("io.appmetrica.analytics:push:4.0.0") {
                exclude group: "io.appmetrica.analytics", module: "push-provider-firebase"
            }
        }
        
    3. Make changes in the application element in the AndroidManifest.xml file:

      <meta-data android:name="ymp_hms_default_app_id" android:value="number:APP_ID"/>
      

      APP_ID — App ID in HMS. You can find it in the app_id field of the agconnect-services.json file. The file can be downloaded from the Huawei console.

The AppMetrica Push SDK can simultaneously work with Firebase and HMS.

Step 3. Initialize the library

Initialize the library in the app — extend the Application class and override the onCreate() method as follows:

Firebase only
class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        AppMetricaPush.activate(applicationContext)
    }
}
public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        AppMetricaPush.activate(getApplicationContext());
    }
}
HMS only
class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        AppMetricaPush.activate(applicationContext, HmsPushServiceControllerProvider(this))
    }
}
public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        AppMetricaPush.activate(getApplicationContext(), new HmsPushServiceControllerProvider(this));
    }
}
Firebase and HMS

Add the following dependency to allow calling FirebasePushServiceControllerProvider(this):

dependencies {
    implementation("io.appmetrica.analytics:push-provider-firebase:$appmetrica_push_version")
}

Override the class:

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

Add the following dependency to allow calling FirebasePushServiceControllerProvider(this):

dependencies {
    implementation "io.appmetrica.analytics:push-provider-firebase:$appmetrica_push_version"
}

Override the class:

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

Alert

The AppMetrica Push SDK library must be initialized in the main process.

Step 4. (Optional) Configure Silent Push Notifications

Configure processing silent push notifications.

  1. Create a special BroadcastReceiver:

    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)
        }
    }
    
    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);
        }
    }
    
  2. Make changes in the application element in the AndroidManifest.xml file:

    <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 — Unique app ID in Gradle (package name). For example, com.example.name.

Step 5. (Optional) Enable push tokens update

Alert

If you have your own service to handle push notifications (a class inherited from FirebaseMessagingService or HmsMessageService), check that you are not handling push notifications from AppMetrica.

To check that the push notification is not from AppMetrica, use the AppMetricaMessagingService.isNotificationRelatedToSDK or AppMetricaHmsMessagingService.isNotificationRelatedToSDK method.

The FCM service can withdraw the push token of the device, for example, if the user did not launch the application for a long time. AppMetrica stores push tokens on the server and can not send a push notification to a device with an obsolete token.

To automatically collect current push token go to the application settings in the AppMetrica interface and enable the Update tokens with a Silent Push notification option in the Push Notifications tab.

Step 6. (Optional) Configure usage with other push SDKs

If you have integrated multiple SDKs for handling push notifications into your app, follow the guide Using with other push services.

Note

You need to make additional settings, otherwise, you may encounter issues with processing push notifications.

Sending additional information

You can send additional information with the push notification if necessary. This data is specified in the AppMetrica web interface when configuring the push campaign.

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

Detecting the application launch via push notification

To distinguish app launches initiated by opening an AppMetrica push notification from the total number of app starts, you should check the Intent action of the app. If you specified a deeplink as the action, this will be the Intent action. If the action is set as opening the app, the Intent action passes the value AppMetricaPush#OPEN_DEFAULT_ACTIVITY_ACTION.

Setting the default icon

To set the default push notification icon, make changes in the application element in the AndroidManifest.xml file:

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

ICON_RESOURCE — Icon resource. For example, @drawable/large_icon.

See also

If you didn't find the answer you were looking for, you can use the feedback form to submit your question. Please describe the problem in as much detail as possible. Attach a screenshot if possible.

Contact support