# SDK Integration

## Onboarding Checklist: Android

Please find the Onboarding Checklist for iOS and Android below. Follow the titles in the checklist to ensure you have completed each essential step in your onboarding process with Netmera.

{% file src="<https://2578508252-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0bOAscrXzPSujyzq8DEz%2Fuploads%2F2JwdGvusPdcbZ11Rwjzo%2FNetmera%20Mobile%20Technical%20Onboarding%20Checklist.xlsx?alt=media&token=971263f1-21d4-4aa0-9fb1-8b0195a08ef6>" %}

## Step 1: Select a Platform <a href="#create-a-firebase-cloud-messaging-configuration" id="create-a-firebase-cloud-messaging-configuration"></a>

1. Navigate to **Developers** > **Netmera Onboarding**.
2. Select **Android** and click **Start** to proceed.

<figure><img src="https://2578508252-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0bOAscrXzPSujyzq8DEz%2Fuploads%2FdnHHTeImCPvN1zhttiqz%2FScreenshot%202025-01-13%20at%2014.27.13.png?alt=media&#x26;token=9d947cca-4a9d-4ea7-a99e-6f1ec57b76f2" alt="" width="563"><figcaption></figcaption></figure>

## Step 2: Create a Firebase Configuration

Netmera uses Firebase Cloud Messaging (FCM) for delivering push notifications.

1. Go to the [Firebase Developers Console](https://console.firebase.google.com/) and create a new project.
2. Generate a new **Private Key** (JSON file) for your project.

{% @arcade/embed flowId="wWs2Yesf5jfbmH6BBLOc" url="<https://app.arcade.software/share/wWs2Yesf5jfbmH6BBLOc>" %}

3. Upload the JSON file you downloaded from Firebase Cloud Messaging to the `Project > app-level root` `directory`.

<figure><img src="https://2578508252-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0bOAscrXzPSujyzq8DEz%2Fuploads%2FdAYe3gTHrGd2QdtgYrKB%2Funnamed.png?alt=media&#x26;token=3ba06e1e-5c8f-4721-b29e-ed086a78c15b" alt="" width="563"><figcaption></figcaption></figure>

4. Choose one of the four options: ***Node.js, Java, Python, and Go***. The choice of option does not require any action. Simply click the 'Generate New Private Key' button to download the file. No further selections are needed.

<figure><img src="https://2578508252-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0bOAscrXzPSujyzq8DEz%2Fuploads%2FieISJLphMq8gqik2ACzh%2Funnamed%20(3).png?alt=media&#x26;token=8ae6f9f6-35cd-47cf-a1e7-4d58de472118" alt="" width="563"><figcaption></figcaption></figure>

5. Upload this file in **Netmera Panel > Developers > Netmera Onboarding > Android > Step 2: Create A Firebase Configuration > FCM Service Account Key.**

<figure><img src="https://2578508252-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0bOAscrXzPSujyzq8DEz%2Fuploads%2Fvv8e7w3bzTK4DeYndjkS%2Fimage.png?alt=media&#x26;token=928530d5-2f8d-4741-9417-b2ffa84d6396" alt="" width="563"><figcaption></figcaption></figure>

## Step 3: Select a Target SDK <a href="#integrate-sdk" id="integrate-sdk"></a>

Select the SDK for your application development framework as **Native Android**.

<figure><img src="https://2578508252-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F0bOAscrXzPSujyzq8DEz%2Fuploads%2F0AgZXdxAZerd8z8HLv5q%2Fimage.png?alt=media&#x26;token=f6a80562-4581-4829-aa5a-0bd65518968b" alt="" width="563"><figcaption></figcaption></figure>

## Step 4: Integrate Netmera SDK <a href="#integrate-sdk" id="integrate-sdk"></a>

<figure><img src="https://lh7-us.googleusercontent.com/5bVVUuZBFS3dRDP9UO2_i31L0jF2Obwpwrh9jIULVFCy5avp84ss9Ntu_VPtVEw93p7ZIYbOc4EZBJhG4AiXU_G-UNz7ZOGg0Udsq5mCmASNUxTQlMI4uPHeR5DOjr_3Q7MCH5f-HQaPutsOBkrzPwk" alt="" width="563"><figcaption></figcaption></figure>

{% hint style="warning" %}
**Important Notes on SDK API Key:**

* **Do not** use the API key from a **test** **panel** in production.
* **Each panel has a unique API key**, and using the wrong one can result in data misdirection or errors.

**To obtain your SDK API Key:**

1. Go to the Netmera Panel.
2. Navigate to Developer > API > SDK API Key.
3. Copy your SDK API Key from this section.
   {% endhint %}

### Standard Gradle&#x20;

If your project is using Standard Gradle:

* Add the following snippets to integrate the Netmera SDK into your project.

{% tabs %}
{% tab title="Project's build.gradle" %}
In this step, only copy the url specified below and add it to maven.&#x20;

```groovy
buildscript {
    repositories {
         google()
         maven {url 'https://developer.huawei.com/repo/'} // only include for HMS copy the url and add it to maven
    }
    dependencies {

    classpath 'com.android.tools.build:gradle:{your_project_android_tools_version}'
    classpath 'com.google.gms:google-services:{your_google_services_version}'
    classpath 'com.huawei.agconnect:agcp:{your_agcp_version}' // only include for HMS 
    }
}

allprojects {
    repositories {
        google()
        maven {url 'https://developer.huawei.com/repo/'} // only include for HMS  copy the url and add it to maven
        maven { url "https://release.netmera.com/release/android" } 
    }
}
```

{% endtab %}

{% tab title="App's build.gradle" %}
You should add Netmera dependency to your dependencies section in your: `build.gradle(:app)`

{% hint style="danger" %}
Check [changelog](https://user.netmera.com/netmera-developer-guide/platforms/android/changelog "mention") to find the SDK versions listed as '4.x.x' below.
{% endhint %}

```groovy
dependencies {

    implementation 'com.netmera:nmcore:4.x.x'
    implementation 'com.netmera:nmfcm:4.x.x'
    implementation 'com.netmera:nmhms:4.x.x'

    // If you only need to support Google services, use the following versions:
    // implementation 'com.netmera:nmcore:4.x.x'
    // implementation 'com.netmera:nmfcm:4.x.x'

    // For applications that only want to support Huawei devices, use these dependencies:
    // implementation 'com.netmera:nmcore:4.x.x'
    // implementation 'com.netmera:nmhms:4.x.x'
}

// Must be added at the bottom of the app's build.gradle
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.huawei.agconnect' // only include for HMS
```

**Netmera BOM (Bill of Materials) Support**&#x20;

{% hint style="warning" %}
BOM support is available starting from version 4.5.0.
{% endhint %}

Using the BOM allows you to manage Netmera SDK versions more easily and ensures compatibility between `nmcore`, `nmfcm`, and `nmhms` modules.

```groovy
dependencies {
    implementation platform('com.netmera:netmera-bom:4.x.x')
    implementation 'com.netmera:nmcore'
    implementation 'com.netmera:nmfcm'
    implementation 'com.netmera:nmhms'

    // If you only need to support Google services, use the following versions:
    // implementation platform('com.netmera:netmera-bom:4.x.x')
    // implementation 'com.netmera:nmcore'
    // implementation 'com.netmera:nmfcm'

    // For applications that only want to support Huawei devices, use these dependencies:
    // implementation platform('com.netmera:netmera-bom:4.x.x')
    // implementation 'com.netmera:nmcore'
    // implementation 'com.netmera:nmhms'
}

// Must be added at the bottom of the app's build.gradle
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.huawei.agconnect' // only include for HMS
```

{% endtab %}
{% endtabs %}

### Gradle Version Catalogs

If your project is using [Gradle Version Catalogs](https://docs.gradle.org/current/userguide/version_catalogs.html):

* Add the following snippets to integrate the Netmera SDK into your project.

#### Kotlin

{% tabs %}
{% tab title="Project's build.gradle" %}

<pre class="language-kotlin"><code class="lang-kotlin"><strong>plugins {
</strong><strong>    alias(libs.plugins.androidApplication) apply false
</strong>    alias(libs.plugins.jetbrainsKotlinAndroid) apply false
<strong>    alias(libs.plugins.google.services) apply false
</strong>    alias(libs.plugins.androidLibrary) apply false
}
</code></pre>

If you want to integrate Huawei Mobile Services (HMS), add the following configuration to your `build.gradle` file before `plugins`. **Following part is only for Huawei integration.**

<pre class="language-kotlin"><code class="lang-kotlin">// This part is only for Huawei integration
buildscript {
    val agpVersion = "project_agp_version"
    val agcpVersion = "agcp_version"
    repositories {
        maven {
            url = uri("https://developer.huawei.com/repo/")
        }
    }
    dependencies {
        classpath("com.android.tools.build:gradle:$agpVersion")
<strong>        classpath("com.huawei.agconnect:agcp:$agcpVersion")on")
</strong>    }
}

plugins {
    ...
}
</code></pre>

**For more information, visit the following link:** [Huawei AppGallery Connect Guide](https://developer.huawei.com/consumer/en/doc/AppGallery-connect-Guides/agc-get-started-android-0000001058210705#EN-US_TOPIC_0000001058750970__p12140631115817).

**Note: Check your `libs.versions.toml` file:**

* This file is usually located within the `gradle` folder in the root directory of your project.
* Review how the relevant plugin is defined.
  {% endtab %}

{% tab title="App's build.gradle " %}

<pre class="language-kotlin"><code class="lang-kotlin">plugins {
    alias(libs.plugins.androidApplication)
    alias(libs.plugins.jetbrainsKotlinAndroid)
<strong>    alias(libs.plugins.google.services)
</strong><strong>    id("com.huawei.agconnect") // only include for HMS
</strong>}
dependencies {
    implementation(libs.netmera.core)
    implementation(libs.netmera.fcm)
<strong>    implementation(libs.netmera.hms) // only include for HMS
</strong>}
</code></pre>

**Netmera BOM (Bill of Materials) Support**&#x20;

{% hint style="warning" %}
BOM support is available starting from version 4.5.0.
{% endhint %}

Using the BOM allows you to manage Netmera SDK versions more easily and ensures compatibility between `nmcore`, `nmfcm`, and `nmhms` modules.

```groovy
dependencies {
    implementation(platform(libs.netmera.bom))
    implementation(libs.netmera.core)
    implementation(libs.netmera.fcm)
    implementation(libs.netmera.hms) // only include for HMS
}
```

{% endtab %}

{% tab title="settings.gradle" %}

```kotlin
dependencyResolutionManagement {
    repositories {
        google() 
        maven { 
          url = uri("https://release.netmera.com/release/android")
        }
        maven {
          url = uri("https://developer.huawei.com/repo/") // only include for HMS
        }
    }
}
```

In this step, only copy the url "<https://release.netmera.com/release/android>" and add it to maven.&#x20;
{% endtab %}

{% tab title="libs.version.toml" %}
{% hint style="warning" %}
Check [changelog](https://user.netmera.com/netmera-developer-guide/platforms/android/changelog "mention") to find the SDK versions listed as '4.x.x' below.
{% endhint %}

```kotlin
[versions]
netmeraCore = "4.x.x"
netmeraFcm = "4.x.x"
netmeraHms = "4.x.x"
googleServices = "your_google_services_version"
[libraries]
netmera-core = { group = "com.netmera", name = "nmcore", version.ref = "netmeraCore" }
netmera-fcm = { group = "com.netmera", name = "nmfcm", version.ref = "netmeraFcm" }
netmera-hms = { group = "com.netmera", name = "nmhms", version.ref = "netmeraHms" } // only include for HMS
[plugins]
google-services = { id = "com.google.gms.google-services", version.ref = "googleServices" }
```

**Netmera BOM (Bill of Materials) Support**&#x20;

{% hint style="warning" %}
BOM support is available starting from version 4.5.0.
{% endhint %}

Using the BOM allows you to manage Netmera SDK versions more easily and ensures compatibility between `nmcore`, `nmfcm`, and `nmhms` modules.

```groovy
[versions]
netmeraBom = "4.x.x"

[libraries]
netmera-bom  = { group = "com.netmera", name = "netmera-bom", version.ref = "netmeraBom" }
netmera-core = { group = "com.netmera", name = "nmcore" }
netmera-fcm  = { group = "com.netmera", name = "nmfcm" }
netmera-hms  = { group = "com.netmera", name = "nmhms" }
```

{% endtab %}
{% endtabs %}

#### Groovy

{% tabs %}
{% tab title="Project's build.gradle" %}

```groovy
plugins {
    alias(libs.plugins.androidApplication) apply false
    alias(libs.plugins.jetbrainsKotlinAndroid) apply false
    alias(libs.plugins.google.services) apply false
    alias(libs.plugins.androidLibrary) apply false
}
```

If you want to integrate Huawei Mobile Services (HMS), add the following configuration to your `build.gradle` file before `plugins`. **Following part is only for Huawei integration.**

<pre class="language-groovy"><code class="lang-groovy">// This part is only for Huawei integration
buildscript {
    val agpVersion = "YOUR_PROJECT_AGP_VERSION" //
    repositories {
<strong>        maven { url 'https://developer.huawei.com/repo/' }
</strong>    }
    dependencies {
        classpath "com.huawei.agconnect:agcp:your_agcp_version"
    }
}

plugins {
    ...
}
</code></pre>

**For more information, visit the following link:** [Huawei AppGallery Connect Guide](https://developer.huawei.com/consumer/en/doc/AppGallery-connect-Guides/agc-get-started-android-0000001058210705#EN-US_TOPIC_0000001058750970__p12140631115817).

**Note: Check your `libs.versions.toml` file:**

* This file is usually located within the `gradle` folder in the root directory of your project.
* Review how the relevant plugin is defined.
  {% endtab %}

{% tab title="App's build.gradle " %}

```groovy
plugins {
    alias(libs.plugins.androidApplication)
    alias(libs.plugins.jetbrainsKotlinAndroid)
    alias(libs.plugins.google.services)
    id("com.huawei.agconnect") // only include for HMS
}
dependencies {
    implementation libs.netmera.core
    implementation libs.netmera.fcm
    implementation libs.netmera.hms // only include for HMS
}
```

**Netmera BOM (Bill of Materials) Support**&#x20;

{% hint style="warning" %}
BOM support is available starting from version 4.5.0.
{% endhint %}

Using the BOM allows you to manage Netmera SDK versions more easily and ensures compatibility between `nmcore`, `nmfcm`, and `nmhms` modules.

```groovy
dependencies {
    implementation platform(libs.netmera.bom)
    implementation libs.netmera.core
    implementation libs.netmera.fcm
    implementation libs.netmera.hms // only include for HMS
}
```

{% endtab %}

{% tab title="settings.gradle" %}

```groovy
dependencyResolutionManagement {
    repositories {
        google()
        maven {
            url "https://release.netmera.com/release/android"
        }
        maven {
            url "https://developer.huawei.com/repo/"
        }
    }
}
```

In this step, only copy the url "<https://release.netmera.com/release/android>" and add it to maven.&#x20;
{% endtab %}

{% tab title="libs.version.toml" %}
{% hint style="warning" %}
Check [changelog](https://user.netmera.com/netmera-developer-guide/platforms/android/changelog "mention") to find the SDK versions listed as '4.x.x' below.
{% endhint %}

```groovy
[versions]
netmeraCore = "4.x.x"
netmeraFcm = "4.x.x"
netmeraHms = "4.x.x" // only include for HMS
googleServices = “your_google_services_version”
[libraries]
netmera-core = { group = "com.netmera", name = "nmcore", version.ref = "netmeraCore" }
netmera-fcm = { group = "com.netmera", name = "nmfcm", version.ref = "netmeraFcm" }
netmera-hms = { group = "com.netmera", name = "nmhms", version.ref = "netmeraHms" } // only include for HMS
[plugins]
google-services = { id = "com.google.gms.google-services", version.ref = "googleServices" }
```

**Netmera BOM (Bill of Materials) Support**&#x20;

{% hint style="warning" %}
BOM support is available starting from version 4.5.0.
{% endhint %}

Using the BOM allows you to manage Netmera SDK versions more easily and ensures compatibility between `nmcore`, `nmfcm`, and `nmhms` modules.

```groovy
[versions]
netmeraBom = "4.x.x"

[libraries]
netmera-bom  = { group = "com.netmera", name = "netmera-bom", version.ref = "netmeraBom" }
netmera-core = { group = "com.netmera", name = "nmcore" }
netmera-fcm  = { group = "com.netmera", name = "nmfcm" }
netmera-hms  = { group = "com.netmera", name = "nmhms" }
```

{% endtab %}
{% endtabs %}

## Step 5: Initialize Netmera SDK <a href="#initialize-netmera" id="initialize-netmera"></a>

### Initialize Netmera SDK Android v4.0.0+

1. Add the following initialization code inside the `onCreate()` method of your `Application` class.

{% hint style="info" %}
**If Application Class is Not Already Present:**

1. Create an Application Class\
   If your project doesn't yet have an `Application` class, create one and include the initialization code as shown below.
2. Update AndroidManifest.xml\
   In the `AndroidManifest.xml`, add your `Application` class by specifying `android:name` in the `<application>` tag.
3. To exclude Netmera Android SDK files from auto-backup if your app supports backup, please see the relevant title [#q10-excluding-netmera-android-sdk-files-from-auto-backup-if-your-app-supports-backup](https://user.netmera.com/netmera-developer-guide/platforms/android/android-integration-faqs#q10-excluding-netmera-android-sdk-files-from-auto-backup-if-your-app-supports-backup "mention").
   {% endhint %}

{% tabs %}
{% tab title="Kotlin" %}
{% hint style="warning" %}
**`registerActivityLifecycleCallbacks`** method must be called in the Main Thread.
{% endhint %}

```kotlin
override fun onCreate() {
    super.onCreate()
    // Must be called on the Main Thread
    registerActivityLifecycleCallbacks(NMActivityLifecycleCallbacks(this))

    val configBuilder = NetmeraConfiguration.Builder()
        .apiKey(apiKey)
        .firebaseSenderId(PropertiesUtil.gcmSenderId)
        .huaweiSenderId(PropertiesUtil.hmsSenderId)  // only include for HMS
        .logging(true)  // enables logging in logcat
        .addProvider(NMFCMProvider())
        .addProvider(NMHMSProvider()) // only include for HMS
    Netmera.init(configBuilder.build(this))
}
```

{% endtab %}

{% tab title="Java" %}
{% hint style="danger" %}
**`registerActivityLifecycleCallbacks`** method must be called in the Main Thread.
{% endhint %}

```java
@Override
public void onCreate() {
    super.onCreate();
    // Must be called on the Main Thread
    registerActivityLifecycleCallbacks(new NMActivityLifecycleCallbacks(this));

    NetmeraConfiguration.Builder configBuilder = new NetmeraConfiguration.Builder();
    configBuilder.apiKey(apiKey)
                 .firebaseSenderId(PropertiesUtil.gcmSenderId)
                 .huaweiSenderId(PropertiesUtil.hmsSenderId)  // only include for HMS
                 .logging(true);  // enable logging in logcat
                 .addProvider(new NMFCMProvider())
                 .addProvider(new NMHMSProvider());  // only include for HMS
    Netmera.init(configBuilder.build(this));
}
```

{% endtab %}
{% endtabs %}

### Removed Components in Android SDK v4.0.0+

If you are using Netmera Android SDK version 4.0.0 or later, or performing an SDK update,

* **Do not** include the following lines of code from previous SDK versions when initializing Netmera SDK.&#x20;
* If these lines are already present in your code, please **remove** them:

```kotlin
// Removed components in SDK 4.0.0
NMInitializer.initializeComponents(this)
AppInitializer.getInstance(this).initializeComponent(NMFCMProviderInitializer::class.java)
AppInitializer.getInstance(this).initializeComponent(NMHMSProviderInitializer::class.java)
```

<details>

<summary><strong>Initializing Netmera SDK Before Android SDK Version 4.0.0</strong></summary>

**Add initialization code in `onCreate()` method:**

1. Add the code below within the `onCreate()` method of your class that extends `android.app.Application.`
2. If your project does not currently have a class that extends `Application`, create one.&#x20;
3. Add the newly created or existing `Application` class to your `AndroidManifest.xml` file using the `android:name` attribute within the `<application>` tag.&#x20;
4. Add initialization code below.

**Kotlin**

```kotlin
override fun onCreate() {
    super.onCreate()

    val configBuilder = NetmeraConfiguration.Builder()
        .apiKey(apiKey)
        .firebaseSenderId(PropertiesUtil.gcmSenderId)
        .huaweiSenderId(PropertiesUtil.hmsSenderId)  // only include for HMS
        .logging(true)  // Allows Netmera logs to appear in logcat
    Netmera.init(configBuilder.build(this))
}
```

**Java**

```java
@Override
public void onCreate() {
    super.onCreate();

    NetmeraConfiguration.Builder configBuilder = new NetmeraConfiguration.Builder();
    configBuilder.apiKey(apiKey)
                 .firebaseSenderId(PropertiesUtil.gcmSenderId)
                 .huaweiSenderId(PropertiesUtil.hmsSenderId) // only include for HMS
                 .logging(true);  // Allows Netmera logs to appear in logcat

    Netmera.init(configBuilder.build(this));
}
```

**Warning: Init Method Must Be Added in the Main Thread**

Ensure that `init` methods are added in the main thread. Adding them in the background may lead to unexpected behavior and potential issues.

<mark style="color:purple;">**Autostart Troubleshooting:**</mark>

After implementing the necessary enhancements above:

1. **Call the Initialization Method**\
   Use the provided initialization method to set up Netmera in your application.
2. **Create `NetmeraConfiguration`**\
   Configure the SDK by creating and passing the required `NetmeraConfiguration` object.

Once these steps are completed, the Netmera SDK will automatically handle the rest. This automation is possible because Netmera leverages Android's **AutoStartup** framework. This framework ensures that certain processes are executed before the initialization method is invoked, streamlining the SDK's setup and operation.

<mark style="color:purple;">**If the AutoStartup Feature is Disabled in Your Application:**</mark>

You can continue using the Netmera SDK by calling the following code block **above the `init` method:**

**Kotlin**

```kotlin
fun onCreate() {
    super.onCreate()
    NMInitializer.initializeComponents(this)
    AppInitializer.getInstance(this).initializeComponent(NMFCMProviderInitializer::class.java)
    AppInitializer.getInstance(this).initializeComponent(NMHMSProviderInitializer::class.java) // only include for HMS       
    ...
    Netmera.init(configBuilder.build(this))
}
```

**Java**

<pre class="language-java"><code class="lang-java">@Override public void onCreate() {
    super.onCreate();
    NMInitializer.initializeComponents(this);
    AppInitializer.getInstance(this).initializeComponent(NMFCMProviderInitializer.class);
    AppInitializer.getInstance(this).initializeComponent(NMHMSProviderInitializer.class); // only include for HMS   
    ...
<strong>    Netmera.init(configBuilder.build(this));
</strong>}
</code></pre>

</details>

{% hint style="info" %}
**Configuring baseUrl for On-Premise Applications**

* **For On-Premise Applications:**\
  Include the following code to configure the base URL and API key:

  ```java
  configBuilder.baseUrl(baseUrl).apiKey(apiKey);
  ```
* **For Non-On-Premise Applications:**\
  Only the API key needs to be configured:

  ```java
  configBuilder.apiKey(apiKey);
  ```

{% endhint %}

### Optional: Initialization Callback

To implement the initialization callback:

1. Add the following code to handle success and failure:

For detailed information, you can visit >[push-callbacks](https://user.netmera.com/netmera-developer-guide/platforms/android/push-notifications/push-callbacks "mention").

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
Netmera.init(
    configBuilder.build(this), 
    object : NMInitSessionListener {
        override fun onSuccess() {
            Log.i("NetmeraApp", "Session init completed")
        }

        override fun onFailure(error: String?) {
            Log.e(
                "NetmeraApp",
                "Error occurred when trying to init session with Netmera. Error::$error"
            )
        }
    }
)
```

{% endtab %}

{% tab title="Java" %}

```java
Netmera.init(
    configBuilder.build(this),
    new NMInitSessionListener() {
        @Override
        public void onSuccess() {
            Log.i("NetmeraApp", "Session init completed");
        }

        @Override
        public void onFailure(String error) {
            Log.e(
                "NetmeraApp",
                "Error occurred when trying to init session with Netmera. Error::" + error
            );
        }
    }
);
```

{% endtab %}
{% endtabs %}

### Optional: Enable Logging

To enable logging for debugging, add the following code in the `onCreate()` method of your `Application` class:

1. **Enable logging**:

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
.logging(true)
```

{% endtab %}

{% tab title="Java" %}

```java
Netmera.logging(true);
```

{% endtab %}
{% endtabs %}

2. **Disable logging for production**:

When preparing your app for release, set `.logging(false)`

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
.logging(false)
```

{% endtab %}

{% tab title="Java" %}

```java
Netmera.logging(false);
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
**Set `.logging (false)` while on prod:**

Before releasing your app to the store, make sure that `.logging` is disabled (set to `false`) in the production environment.
{% endhint %}

## Step 6: Android 13 Push Notification Permissions <a href="#about-android-13-push-notification-permissions" id="about-android-13-push-notification-permissions"></a>

Android 13 introduced significant changes to how push notification permissions are handled.

* **Increased User Control:** Apps targeting **API Level 33 and above** now have more control over when and how they request push notification permissions. This allows for a more user-friendly and context-aware permission request experience.
* **Automatic Permission Requests for Older Apps:** For apps targeting **API Level 32 and before** running on Android 13, the system automatically prompts the user for push notification permission when the app creates its first notification channel.

**Impact on Netmera SDK Users:**

The Netmera SDK initializes and creates notification channels during the app's startup. Consequently:

* **On Android 13:** For apps targeting API Level 32 and below, this initialization process will trigger the automatic system prompt for push notification permission.
* **On Android 12 and below:** The system generally assumes push notification permission has already been granted.

{% hint style="success" %}
If you initialize the Netmera SDK at app startup (which is recommended), the system will automatically request push notification permissions on Android 13 devices for apps targeting API Level 32 and before. For devices running Android 12 or earlier, the system assumes permission is already granted.
{% endhint %}

### Push Permission Methods in Netmera SDK

For applications targeting API 33, Netmera SDK offers two key methods for requesting push permission:

1. **Requesting Push Permission**

* Add this method in the `onCreate()` method of your `MainActivity`, below `super.onCreate(savedInstanceState)` to request push notification permissions from the user.

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
Netmera.requestNotificationPermissions(this)
```

{% endtab %}

{% tab title="Java" %}

```java
Netmera.requestNotificationPermissions(this);
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Push Enable/Disable User Flow**

1. **Granting Permission:**
   * The user triggers `requestNotificationPermissions()`, and if they grant permission, a push enable request is sent.

2. **Handling Denial:**
   * If the user denies permission, avoid resending the request immediately (as recommended by Google). Instead, the SDK opens the app's notification settings. The user can grant permission from the settings and return to the app, where a push enable request is sent.

3. **Denying Permission:**
   * If the user triggers `requestNotificationPermissions()` and denies permission, a push disable request is sent.

4. **Reattempt After Denial:**
   * If denied, avoid immediate re-request. The SDK will open the app's notification settings. If the user cancels (presses the back button), a push disable request is sent.
     {% endhint %}

5. **Checking Notification Status**

* This method allows checking whether the necessary permissions for the application have been obtained.

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
checkNotificationPermission()
```

{% endtab %}

{% tab title="Java" %}

```java
checkNotificationPermission()
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Responses**

When this method is called, it would return one of the following responses:

1. **NOTDETERMINED**\
   The user has opened the app but hasn't made a decision about notification permissions yet.

2. **GRANTED**\
   The user has granted notification permission, and the app can send notifications.

3. **DENIED**\
   The user has denied permission or has blocked notifications through system settings.
   {% endhint %}

4. **Managing Push Notifications**

Netmera Android SDK provides methods to enable or disable push notifications programmatically. This can be useful when offering users the ability to manage their notification preferences directly within the app.

```java
// Enables push notifications
Netmera.enablePush();

// Disables push notifications
Netmera.disablePush();
```

### Firebase Messaging Service Class

{% hint style="danger" %}

## Required for Firebase & HMS integrations

If your platform uses a **custom `FirebaseMessagingService`** or **`HmsMessageService`**, you must update your `AndroidManifest.xml` file to avoid service conflicts with Netmera.
{% endhint %}

#### Step 1 : Manifest Configuration

**For Custom `FirebaseMessagingService`:**

If you are using your own `FirebaseMessagingService` class, make sure to add the following line to your `AndroidManifest.xml` to remove Netmera's default FCM service:

```xml
<service
    android:name="com.netmera.nmfcm.NMFirebaseService"
    tools:node="remove" />
```

**For Custom `HmsMessageService`:**

If you are using your own `HmsMessageService` class, include the following entry in your manifest to remove Netmera’s default HMS service:

```xml
<service
    android:name="com.netmera.nmhms.NMHuaweiService"
    tools:node="remove" />
```

#### Step 2:  FCM and HMS Implementations

{% hint style="warning" %}

## **Deprecated Methods (Before v4.0.12)**

The following method is **deprecated** as of Netmera SDK **v4.0.12** and must not be used in new implementations:

**Deprecated:**

```kotlin
Netmera.isNetmeraRemoteMessage(remoteMessage)
```

**Use instead:**

* `Netmera.isNetmeraRemoteMessage(remoteMessage.data)` for FCM
* `Netmera.isNetmeraRemoteMessage(remoteMessage.dataOfMap)` for HMS

Make sure your codebase reflects these updated signatures to avoid compatibility issues with Netmera push handling.
{% endhint %}

**For Custom `FirebaseCloudMesssaging` (FCM)**

```kotlin
// For FirebaseCloudMesssaging (FCM)
override fun onMessageReceived(remoteMessage: RemoteMessage) {
    super.onMessageReceived(remoteMessage)

    if (Netmera.isNetmeraRemoteMessage(remoteMessage.data)) {
        Netmera.onNetmeraPushMessageReceived(remoteMessage)
    } else {
        // Handle other messages
    }
}
```

**For Custom `HmsMessageService` (HMS):**

```kotlin
// For Custom HmsMessageService (HMS)
override fun onMessageReceived(remoteMessage: RemoteMessage) {
    super.onMessageReceived(remoteMessage)

    if (Netmera.isNetmeraRemoteMessage(remoteMessage.dataOfMap)) {
        Netmera.onNetmeraPushMessageReceived(remoteMessage)
    } else {
        // Handle other messages
    }
}
```

**Handling Token Updates**

You must also report HMS push tokens to Netmera:

```kotlin
override fun onNewToken(token: String) {
    super.onNewToken(token)
    Netmera.onNetmeraNewToken(token)
}
```

{% hint style="info" %}
**Important Note for Obfuscation:**

No special obfuscation rules are needed for Netmera. Its functionality remains unaffected, even with code obfuscation enabled.
{% endhint %}

### Optional: Email Permission Preferences

In version 3.9.18, the **Email Preferences** feature allows you to **request email permission** from users. Use the following method to manage email permission:

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
fun setEmailPermission(isAllowed: Boolean) 
```

{% endtab %}

{% tab title="Java" %}

```java
public static void setEmailPermission(boolean isAllowed);
```

{% endtab %}
{% endtabs %}

**Revoking Email Permission:**

* To revoke email permission, execute the following code:

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
Netmera.setEmailPermission(false)
```

{% endtab %}

{% tab title="Java" %}

```java
Netmera.setEmailPermission(false);
```

{% endtab %}
{% endtabs %}

**Granting Email Permission:**

* To grant email permission, execute:

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
Netmera.setEmailPermission(true)
```

{% endtab %}

{% tab title="Java" %}

```java
Netmera.setEmailPermission(true);
```

{% endtab %}
{% endtabs %}

## Push Callbacks <a href="#sdk-integration-complete" id="sdk-integration-complete"></a>

Netmera provides the following push callbacks for better push notification management:

* *Push Register, Push Receive, Push Open, Push Dismiss, Push Button Click.*

For detailed implementation, please refer to the full documentation > [push-callbacks](https://user.netmera.com/netmera-developer-guide/platforms/android/push-notifications/push-callbacks "mention")

## Android SDK Integration Complete <a href="#sdk-integration-complete" id="sdk-integration-complete"></a>

The Android SDK integration has been successfully completed, and your devices are now set to receive the following types of push notifications via the Netmera Dashboard:

* **Standard Push Notifications**
* **Interactive Push Notifications**
* **Widgets**
* **Push Notifications with Deeplinks**

{% hint style="warning" %}

#### **Warning During App Store Submission:**

When submitting your application to the App Store, you might encounter the `com.google.android.gms.permission.AD_ID` alert. Here’s how to handle it:

1. Choose **'Yes'** when prompted.
2. On the subsequent page, make sure the **'analytics'** option is selected.
3. After this, no further additions to the manifest are required; simply merging the manifest will suffice.
   {% endhint %}
