# Android

## How to create a project in Firebase and integrate Firebase Services into your application

Push Notifications on Android are sent with the help of the FCM service.

Register and open the project creation window in Firebase.

<figure><img src="/files/BoMfecWVKyEXjbjaS5Yd" alt="" width="563"><figcaption></figcaption></figure>

Click Add project.

<figure><img src="/files/trVmPQ4yudkDOckc3RJ5" alt="" width="563"><figcaption></figcaption></figure>

Write the name of your project. At this stage, you can also set your own unique project identifier or use the one that Firebase will generate for you automatically.

<figure><img src="/files/4zWpq3foZ1dIKrE2q0fh" alt="" width="563"><figcaption></figcaption></figure>

After creating the project card, create an Android application by clicking on the Android icon.

<figure><img src="/files/DHlEqS16zW4mr3IfRQSr" alt="" width="375"><figcaption></figcaption></figure>

Register your android package name.

<figure><img src="/files/BWJWaHN0TvTV3lAdx7u0" alt="" width="563"><figcaption></figcaption></figure>

Download the google-services.json file and use it according to the instructions of firebase.

<figure><img src="/files/u8rAnOop3hvsN6o819WI" alt="" width="563"><figcaption></figcaption></figure>

Add firebase dependencies according to the firebase documentation.

<figure><img src="/files/CefyA4QcZQEZgmnptmFD" alt="" width="563"><figcaption></figcaption></figure>

Complete the application registration, you will see the project overview section.

<figure><img src="/files/mhrOQJbww8fH0pFcm1D8" alt="" width="563"><figcaption></figcaption></figure>

Select your application by clicking on it, you will see a gear on the right side, click on it to go to project settings.

<figure><img src="/files/63pRJFjNUPea4usnatw8" alt="" width="533"><figcaption></figcaption></figure>

Go to the cloud messages section, make sure that the Firebase Cloud Messaging API (V1) is active (if not, activate it).

<figure><img src="/files/wPPODWigaLr0iiAlkAJr" alt="" width="563"><figcaption></figcaption></figure>

Go to the general section and copy the value of the Project ID field and paste it into the devtodev web interface.

<figure><img src="/files/YGKg6q2cc7OkClWcix15" alt="" width="563"><figcaption></figcaption></figure>

The Project ID is also available from the Firebase main screen in the project cards. After setting up the application, the card should look like this:

<figure><img src="/files/ZT382kpiLSSTp7moHBF7" alt="" width="563"><figcaption></figcaption></figure>

It should have a Project ID and an android icon.

Next, open the push notifications integration settings panel in the application settings section in devtodev service (App → Settings → Push notifications → Push notifications panel). Push edit button (pencil symbol).

<figure><img src="/files/GIFXIrjC3C991Y4JhH4L" alt=""><figcaption></figcaption></figure>

You will need to specify the Firebase Project ID and authorize devtodev to send messages and manage messaging subscriptions for your Firebase application. To authorise the application, you must use Google login and password of a user with sufficient access rights to the project on Firebase.\
After that click Save button.

## Messaging Module Integration

The Messaging module is available as an AAR (recommended) and JAR library. The library is available in the MavenCentral and [GitHub repository](https://github.com/devtodev-analytics/android-sdk-2.0).

1\. If you use Gradle for the applications build, add **`mavenCentral()`** into ***gradle.build*** file of your application and specify the following relationship in dependencies block:

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

```kotlin
defaultConfig {
    //other existing fields 
    versionName = "1.0" //your app version (required)
}

dependencies {
    // Requirement
    implementation("androidx.appcompat:appcompat:*.*.*")
    implementation("com.google.code.gson:gson:*.*.*")
    implementation("com.google.firebase:firebase-messaging:*.*.*")
    implementation("com.google.android.gms:play-services-ads-identifier:*.*.*")
    
    // if you use AAR (recommended) or JAR downloaded from GitHub, please add:
    implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.aar"))))
    
    // or just add the dependency, get the latest version from
    // https://mvnrepository.com/artifact/com.devtodev/android-analytics
    implementation("com.devtodev:android-analytics:*.*.*")
    // https://mvnrepository.com/artifact/com.devtodev/android-messaging
    implementation("com.devtodev:android-messaging:*.*.*")
    
    // Optional (recommended)
    implementation("com.android.installreferrer:installreferrer:*.*")
}
```

{% endtab %}

{% tab title="Groovy" %}

```groovy
defaultConfig {
    //other existing fields 
    versionName "1.0" //your app version (required)
}

dependencies {
    // Requirement
    implementation 'androidx.appcompat:appcompat:*.*.*'
    implementation 'com.google.code.gson:gson:*.*.*'
    implementation 'com.google.android.gms:play-services-ads-identifier:*.*.*'
    implementation 'com.google.firebase:firebase-messaging:*.*.*'
    
    // if you use AAR (recommended) or JAR downloaded from GitHub, please add:
    implementation fileTree(dir: "libs", include: ["*.aar"]) 
    
    // or just add the dependency, get the latest version from
    // https://mvnrepository.com/artifact/com.devtodev/android-analytics
    implementation 'com.devtodev:android-analytics:*.*.*'
    // https://mvnrepository.com/artifact/com.devtodev/android-messaging
    implementation 'com.devtodev:android-messaging:*.*.*'
    
    // Optional (recommended)
    implementation 'com.android.installreferrer:installreferrer:*.*'
}
```

{% endtab %}
{% endtabs %}

2\. To the app manifest add the following:

<pre class="language-xml"><code class="lang-xml">&#x3C;!-- permission.POST_NOTIFICATIONS for API level 33 or higher -->
&#x3C;uses-permission android:name=“android.permission.POST_NOTIFICATIONS”/>

<strong>&#x3C;application>
</strong>        &#x3C;service
            android:name="com.devtodev.push.internal.logic.DTDFcmMessagingService"
            android:exported="true">
            &#x3C;intent-filter>
                &#x3C;action android:name="com.google.firebase.MESSAGING_EVENT"/>
            &#x3C;/intent-filter>
        &#x3C;/service>

        &#x3C;receiver
            android:name="com.devtodev.push.internal.logic.PushClickReceiver"
            android:enabled="true"
            android:exported="true">
            &#x3C;intent-filter>
                &#x3C;action android:name="com.devtodev.android.push.CLICKED" />
            &#x3C;/intent-filter>
        &#x3C;/receiver>
&#x3C;/application>
</code></pre>

3\. To add a user icon to your push notification and change its color, add the following strings to the manifest file code:

```markup
<meta-data
 android:name="com.devtodev.push.default_small_icon"
 android:resource="@drawable/ic_icon_name" />

<meta-data
 android:name="com.devtodev.push.default_small_icon_color"
 android:resource="@color/icon_color" />
```

To add a large user icon to your push notifications, add:

```markup
<meta-data
android:name="com.devtodev.push.default_large_icon"
android:resource="@mipmap/ic_large_icon_name"/>
```

Example:

```markup
<application
    <!-- Your tags -->
    <service
        android:name="com.devtodev.push.internal.logic.DTDFcmMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <receiver
        android:name="com.devtodev.push.internal.logic.PushClickReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.devtodev.android.push.CLICKED" />
        </intent-filter>
    </receiver>

    <meta-data
        android:name="com.devtodev.push.default_small_icon"
        android:resource="@drawable/ic_baseline" />

    <meta-data
        android:name="com.devtodev.push.default_small_icon_color"
        android:resource="@color/colorPrimary" />

    <meta-data
        android:name="com.devtodev.push.default_large_icon"
        android:resource="@mipmap/baseline_accessibility_black_18"/>
</application>
```

4\. After the **`DTDAnalytics`** initializer, add the **`DTDMessaging`** initializer.

Example:&#x20;

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

```kotlin
val analyticsConfiguration = DTDAnalyticsConfiguration()
analyticsConfiguration.logLevel = DTDLogLevel.Error

DTDAnalytics.initialize(
    appKey = "projectKey",
    analyticsConfiguration = analyticsConfiguration,
    context = this
)
DTDMessaging.initialize(context = this)
```

{% endtab %}

{% tab title="Java" %}

```java
DTDAnalyticsConfiguration analyticsConfiguration = new DTDAnalyticsConfiguration();
analyticsConfiguration.setLogLevel(DTDLogLevel.Error);
DTDAnalytics.INSTANCE.initialize("projectKey",analyticsConfiguration,context);
DTDMessaging.INSTANCE.initialize(context);
```

{% endtab %}
{% endtabs %}

5\. Subscribe a **`DTDPushListener`** to receive information about the **`DTDMessaging`** functioning.

Example:

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

```kotlin
DTDMessaging.setPushListener(object : DTDPushListener {
      override fun onPushServiceRegistrationSuccessful(deviceId: String) {
          //do something
      }
      override fun onPushServiceRegistrationFailed(error: String) {
          //do something
      }
      override fun onPushNotificationReceived(message: Map<String, String?>?) {
          //do something
      }
      override fun onPushNotificationOpened(pushMessage: DTDPushMessage, actionButton: DTDActionButton?) {
          //do something
      }
})
```

{% endtab %}

{% tab title="Java" %}

```java
DTDMessaging.INSTANCE.setPushListener(new DTDPushListener() {
    @Override
    public void onPushServiceRegistrationSuccessful(@NonNull String deviceId) {
        //do something            
    }

    @Override
    public void onPushServiceRegistrationFailed(@NonNull String error) {
        //do something
    }

    @Override
    public void onPushNotificationReceived(@Nullable Map<String, String> message) {
        //do something
    }

    @Override
    public void onPushNotificationOpened(@NonNull DTDPushMessage dtdPushMessage, @Nullable DTDActionButton dtdActionButton) {
        //do something
    }
});
```

{% endtab %}
{% endtabs %}

6\. Call the **`DTDMessaging.startPushService()`** method to activate the Messaging module.

### Android 13 or higher

When using Android 13 or higher, notifications are disabled by default. The app won’t receive notifications until you request a new permission (`POST_NOTIFICATIONS`) and the user grants this permission to your app.

For notifications to work properly, add the following line to the manifest file:

```xml
<uses-permission android:name=“android.permission.POST_NOTIFICATIONS”/>
```

You can check the operation of the `POST_NOTIFICATIONS` permission in your app by inserting this example in the code:

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

```kotlin
@RequiresApi(33)
private fun notificationPermissionIsGranted(): Boolean {
    val res = context.checkCallingOrSelfPermission(POST_NOTIFICATIONS)
    return res == PackageManager.PERMISSION_GRANTED
}
```

{% endtab %}

{% tab title="Java" %}

```java
@RequiresApi(33)
private Boolean notificationPermissionIsGranted() {
    int res = context.checkCallingOrSelfPermission(POST_NOTIFICATIONS);
    return res == PackageManager.PERMISSION_GRANTED;
}
```

{% endtab %}
{% endtabs %}

If the check results in a negative answer (access is not granted), call this method:&#x20;

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

```kotlin
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), yourCode)
```

{% endtab %}

{% tab title="Java" %}

```java
String[] permissionsArr = {Manifest.permission.POST_NOTIFICATIONS};
requestPermissions(permissionsArr, yourCode);
```

{% endtab %}
{% endtabs %}

Its execution will call a dialog that in turn will ask the user to opt in:&#x20;

<figure><img src="/files/Zxb01bLHKKM33pI6LvKb" alt=""><figcaption></figcaption></figure>

This code is going to help you get the user’s decision:&#x20;

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

```kotlin
override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<String?>,
    grantResults: IntArray
) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    if (requestCode == yourCode) {
        if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //permission is granted
        } else {
            //permission is not granted, notifications are not available
        }
    }
}
```

{% endtab %}

{% tab title="Java" %}

```java
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == yourCode) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //permission is granted
        } else {
            //permission is not granted, notifications are not available
        }
    }
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
Note. In SDK ver. 2.1.5 or higher, if the permission is not granted, you will see this message in the log from DTDMessaging: “Notifications don’t work. Permission android.permission.POST\_NOTIFICATIONS is not granted”.
{% endhint %}

### External interface of the `DTDMessaging` **module**

| **Object**                                                                                                                                                                         | **Description**                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`DTDMessaging`**                                                                                                                                                                 | The main object for push notification initialization.                                                                                                                                                                                                                                                                                                                                                                                                                        |
| **`DTDMessaging.initialize(Context context)`**                                                                                                                                     | The push notification initialization method.                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| **`DTDMessaging.startPushService()`**                                                                                                                                              | The push notification activation method. It passes the **`isAllowed`** current state.                                                                                                                                                                                                                                                                                                                                                                                        |
| **`DTDMessaging.pushNotificationsAllowed`** = true or false                                                                                                                        | <p>A property responsible for the activation/deactivation of push notifications.<br></p><p>Functions as a getter (describes the current state) and a setter (sets the current state).<br></p><p>When the state transitions, it sends a pt with <strong><code>isAllowed</code></strong> (<em><strong>true</strong></em> or <em><strong>false</strong></em>) status to the server.<br></p><p>The <strong><code>isAllowed</code></strong> flag status is stored in the SDK.</p> |
| **`DTDMessaging.setIntent(Intent intent)`**                                                                                                                                        | A method of passing a user intent to the SDK using PushMessage.                                                                                                                                                                                                                                                                                                                                                                                                              |
| <p>Written in the manifest file<br><strong><code>\<meta-data android:name="com.devtodev.push.default\_small\_icon" android:resource="@drawable/smallIcon" /></code></strong></p>   | Sets a small custom user icon.                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| <p>Written in the manifest file<br><strong><code>\<meta-data android:name="com.devtodev.default\_small\_icon\_color" android:resource="@color/colorPrimary" /></code></strong></p> | Sets a color of the small custom user icon.                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| <p>Written in the manifest file<br><strong><code>\<meta-data android:name="com.devtodev.push.default\_large\_icon" android:resource="@mipmap/largeIcon" /></code></strong></p>     | Sets a large custom user icon.                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| **`DTDMessaging.getToken()`**                                                                                                                                                      | Returns a push notification registration token (**`firebaseToken`**).                                                                                                                                                                                                                                                                                                                                                                                                        |
| **`DTDMessaging.processPushNotification(Context context, RemoteMessage remoteMessage)`**                                                                                           | Used to pass the push notification to the FirebaseMessagingService if it was implemented by the client but not by the SDK.                                                                                                                                                                                                                                                                                                                                                   |
| **`DTDMessaging.setPushListener(DTDPushListener pushListener)`**                                                                                                                   | (**`DTDPushListener pushListener`**) - sets a listener for push notification event trapping.                                                                                                                                                                                                                                                                                                                                                                                 |

### `DTDPushListener` Interface Methods

| DTDPushListener Interface Methods                                                                  | Description                                                           |
| -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| **`onPushServiceRegistrationSuccessful(String deviceId)`**                                         | Returns a push notification registration token (**`firebaseToken`**). |
| **onPushServiceRegistrationFailed(String error)**                                                  | Returns errors during push notification registration.                 |
| **`onPushNotificationReceived(Map<String, String> message)`**                                      | Returns a directory with data for improving your push notifications.  |
| **`onPushNotificationOpened(DTDPushMessage pushMessage, @Nullable DTDActionButton actionButton)`** | Returns **`pushMessage`** and **`actionButton`** if they were tapped. |

### A Class for Receiving Notification Data (**`DTDPushMessage`**).

#### Basic Class Properties

| Property                                       | Type                   | Description                                                                                                                                                                                                                                                                                        |
| ---------------------------------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`getData()`**                                | Map\<String, String>   | Complete information sent with the use of a remote push notification.                                                                                                                                                                                                                              |
| **`systemId`**                                 | Int                    | The notification ID used in the devtodev system.                                                                                                                                                                                                                                                   |
| **`getTitle(context:Context)`**                | String?                | Returns the selected message title or app name if the former is unavailable.                                                                                                                                                                                                                       |
| **`body`**                                     | String?                | The text body.                                                                                                                                                                                                                                                                                     |
| **`group`**                                    | String?                | A group of messages.                                                                                                                                                                                                                                                                               |
| **`getSound(context: Context)`**               | Uri?                   | Returns the storage path of an audio file.                                                                                                                                                                                                                                                         |
| **`getSoundName()`**                           | String?                | The notification sound name.                                                                                                                                                                                                                                                                       |
| **`tag`**                                      | String?                | The notification tag.                                                                                                                                                                                                                                                                              |
| **`color`**                                    | String?                | The notification color.                                                                                                                                                                                                                                                                            |
| **`bigPicture`**                               | String?                | The notification banner if specified.                                                                                                                                                                                                                                                              |
| **`actionType`**                               | DTDActionType          | <p>The property that returns an enum’s DTDActionType value.<br></p><p>Possible values:</p><ul><li><em><strong>Url</strong></em> - an external link opening</li><li><em><strong>Share</strong></em> - content sharing</li><li><em><strong>Deeplink</strong></em> - an in-app link opening</li></ul> |
| **`actionString`**                             | String?                | The property that returns an optional action ID.                                                                                                                                                                                                                                                   |
| **`getIcon(context: Context, userIcon: Int)`** | Int                    | The icon resource identifier specified by the user (if specified).                                                                                                                                                                                                                                 |
| **`largeIcon`**                                | String?                | The large notification icon name.                                                                                                                                                                                                                                                                  |
| **`actions`**                                  | List\<DTDActionButton> | The list of action buttons used in the push notification.                                                                                                                                                                                                                                          |
| **`isApiSource`**                              | Boolean                | Specifies whether the push notification was sent using the devtodev API.                                                                                                                                                                                                                           |

### A Class for Handling the Notification Button Taps (**`DTDActionButton`**)

| Property           | Type          | Description                                                                                                                                                                                                                                                                                                                                                                              |
| ------------------ | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`Id`**           | String?       | The property that returns the tapped button ID.                                                                                                                                                                                                                                                                                                                                          |
| **`actionString`** | String?       | The property that returns the optional action ID.                                                                                                                                                                                                                                                                                                                                        |
| **`actionType`**   | DTDActionType | <p>The property that returns an enum’s <strong><code>DTDActionType</code></strong> value.<br></p><p>Possible values:</p><ul><li><em><strong>App</strong></em> - a default value</li><li><em><strong>Url</strong></em> - an external link opening</li><li><em><strong>Share</strong></em> - content sharing</li><li><em><strong>Deeplink</strong></em> - an in-app link opening</li></ul> |
| **`icon`**         | String?       | The property that returns the button’s icon name.                                                                                                                                                                                                                                                                                                                                        |
| **`isBackground`** | Boolean       | The button-click app open mode.                                                                                                                                                                                                                                                                                                                                                          |
| **`text`**         | String?       | The property that returns the text of the tapped button.                                                                                                                                                                                                                                                                                                                                 |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.devtodev.com/integration/integration-of-sdk-v2/push-notifications/android.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
