# Sending and Receiving Notifications

> \[!CAUTION]
>
> Twilio deprecated Notify in October 2022 and no longer supports it. Learn more about [transitioning off Notify](https://support.twilio.com/hc/en-us/articles/11746930233115-Transitioning-off-Notify).
>
> If you're starting a new project, use [Programmable Messaging](/docs/messaging) for SMS notifications. For push notifications, integrate directly with platform-specific services such as APNs for iOS or FCM for Android. If you've already built on Notify, visit the [transition guide](https://support.twilio.com/hc/en-us/articles/11746930233115-Transitioning-off-Notify) to learn about your options.

In this guide, we will review different scenarios for sending notifications with Notify, like using **identity** and **tags**, and show different useful tricks on **how to receive Push notifications on iOS and Android devices**.

**Note**, that to be able to send notifications, you first need to [create bindings](/docs/notify/api/binding-resource) and to receive Push notifications on both iOS and Android, you first need to **configure Push Notifications** and **register a device to receive Push Notifications**.

Check out our other guides, that explain how to do that:

* [Bindings resource](/docs/notify/api/binding-resource)
* [Configuring iOS Push Notifications](/docs/notify/configure-ios-push-notifications)
* [Registering for Notifications on iOS](/docs/notify/register-for-notifications-ios)
* [Configuring Android Push Notifications](/docs/notify/configure-android-push-notifications)
* [Registering for Notifications on Android](/docs/notify/register-for-notifications-android)

Once you have that done, you will be able to send and receive notifications. So let's get to it!

## Table of Contents

* [Sending Notifications](#sending-notifications)
* [Notifications on iOS](#notifications-on-ios)
* [Notifications on Android](#notifications-on-android)

## Sending Notifications

***

We'll want to send a `POST` request to Twilio from **notify.js**
in our server app. The request should authenticate using your [Twilio Account SID and Auth Token](https://www.twilio.com/user/account/settings).
It should also identify who to send a notification to by either their
**identity** or **tags**.

We'll use **identity** if we want a notification
to be sent to all devices with Bindings associated with a given identity.

Send a Notification (identity)

```js
// Download the helper library from https://www.twilio.com/docs/node/install
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

async function createNotification() {
  const notification = await client.notify.v1
    .services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
    .notifications.create({
      body: "Hello Bob",
      identity: ["00000001"],
    });

  console.log(notification.sid);
}

createNotification();
```

```python
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)

notification = client.notify.v1.services(
    "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
).notifications.create(body="Hello Bob", identity=["00000001"])

print(notification.sid)
```

```csharp
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Notify.V1.Service;
using System.Threading.Tasks;
using System.Collections.Generic;

class Program {
    public static async Task Main(string[] args) {
        // Find your Account SID and Auth Token at twilio.com/console
        // and set the environment variables. See http://twil.io/secure
        string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var notification = await NotificationResource.CreateAsync(
            body: "Hello Bob",
            identity: new List<string> { "00000001" },
            pathServiceSid: "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");

        Console.WriteLine(notification.Sid);
    }
}
```

```java
// Install the Java helper library from twilio.com/docs/java/install

import java.util.Arrays;
import com.twilio.Twilio;
import com.twilio.rest.notify.v1.service.Notification;

public class Example {
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
    public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        Notification notification = Notification.creator("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                                        .setBody("Hello Bob")
                                        .setIdentity(Arrays.asList("00000001"))
                                        .create();

        System.out.println(notification.getSid());
    }
}
```

```go
// Download the helper library from https://www.twilio.com/docs/go/install
package main

import (
	"fmt"
	"github.com/twilio/twilio-go"
	notify "github.com/twilio/twilio-go/rest/notify/v1"
	"os"
)

func main() {
	// Find your Account SID and Auth Token at twilio.com/console
	// and set the environment variables. See http://twil.io/secure
	// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
	client := twilio.NewRestClient()

	params := &notify.CreateNotificationParams{}
	params.SetBody("Hello Bob")
	params.SetIdentity([]string{
		"00000001",
	})

	resp, err := client.NotifyV1.CreateNotification("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
		params)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		if resp.Sid != nil {
			fmt.Println(*resp.Sid)
		} else {
			fmt.Println(resp.Sid)
		}
	}
}
```

```php
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "/path/to/vendor/autoload.php";

use Twilio\Rest\Client;

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = getenv("TWILIO_ACCOUNT_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);

$notification = $twilio->notify->v1
    ->services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
    ->notifications->create([
        "body" => "Hello Bob",
        "identity" => ["00000001"],
    ]);

print $notification->sid;
```

```ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'twilio-ruby'

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)

notification = @client
               .notify
               .v1
               .services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
               .notifications
               .create(
                 body: 'Hello Bob',
                 identity: [
                   '00000001'
                 ]
               )

puts notification.sid
```

```bash
# Install the twilio-cli from https://twil.io/cli

twilio api:notify:v1:services:notifications:create \
   --service-sid ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \
   --body "Hello Bob" \
   --identity 00000001
```

```bash
curl -X POST "https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Notifications" \
--data-urlencode "Body=Hello Bob" \
--data-urlencode "Identity=00000001" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
```

```json
{
  "sid": "NTb8021351170b4e1286adaac3fdd6d082",
  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "date_created": "2016-03-24T23:42:28Z",
  "identities": [
    "jing"
  ],
  "tags": [],
  "segments": [],
  "priority": "high",
  "ttl": 2419200,
  "title": "test",
  "body": "Hello Bob",
  "sound": null,
  "action": null,
  "data": null,
  "apn": null,
  "fcm": null,
  "gcm": null,
  "sms": null,
  "facebook_messenger": null,
  "alexa": null
}
```

If we want to send a notification to a particular Binding of a user, we can use **identity** and **tags** together.

Send a Notification (Identity and Tag)

```js
// Download the helper library from https://www.twilio.com/docs/node/install
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

async function createNotification() {
  const notification = await client.notify.v1
    .services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
    .notifications.create({
      body: "Hello Bob",
      identity: ["00000001"],
      tag: ["preferred_device"],
    });

  console.log(notification.sid);
}

createNotification();
```

```python
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)

notification = client.notify.v1.services(
    "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
).notifications.create(
    body="Hello Bob", identity=["00000001"], tag=["preferred_device"]
)

print(notification.sid)
```

```csharp
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Notify.V1.Service;
using System.Threading.Tasks;
using System.Collections.Generic;

class Program {
    public static async Task Main(string[] args) {
        // Find your Account SID and Auth Token at twilio.com/console
        // and set the environment variables. See http://twil.io/secure
        string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var notification = await NotificationResource.CreateAsync(
            body: "Hello Bob",
            identity: new List<string> { "00000001" },
            tag: new List<string> { "preferred_device" },
            pathServiceSid: "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");

        Console.WriteLine(notification.Sid);
    }
}
```

```java
// Install the Java helper library from twilio.com/docs/java/install

import java.util.Arrays;
import com.twilio.Twilio;
import com.twilio.rest.notify.v1.service.Notification;

public class Example {
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
    public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        Notification notification = Notification.creator("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                                        .setBody("Hello Bob")
                                        .setIdentity(Arrays.asList("00000001"))
                                        .setTag(Arrays.asList("preferred_device"))
                                        .create();

        System.out.println(notification.getSid());
    }
}
```

```go
// Download the helper library from https://www.twilio.com/docs/go/install
package main

import (
	"fmt"
	"github.com/twilio/twilio-go"
	notify "github.com/twilio/twilio-go/rest/notify/v1"
	"os"
)

func main() {
	// Find your Account SID and Auth Token at twilio.com/console
	// and set the environment variables. See http://twil.io/secure
	// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
	client := twilio.NewRestClient()

	params := &notify.CreateNotificationParams{}
	params.SetBody("Hello Bob")
	params.SetIdentity([]string{
		"00000001",
	})
	params.SetTag([]string{
		"preferred_device",
	})

	resp, err := client.NotifyV1.CreateNotification("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
		params)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		if resp.Sid != nil {
			fmt.Println(*resp.Sid)
		} else {
			fmt.Println(resp.Sid)
		}
	}
}
```

```php
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "/path/to/vendor/autoload.php";

use Twilio\Rest\Client;

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = getenv("TWILIO_ACCOUNT_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);

$notification = $twilio->notify->v1
    ->services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
    ->notifications->create([
        "body" => "Hello Bob",
        "identity" => ["00000001"],
        "tag" => ["preferred_device"],
    ]);

print $notification->sid;
```

```ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'twilio-ruby'

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)

notification = @client
               .notify
               .v1
               .services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
               .notifications
               .create(
                 body: 'Hello Bob',
                 identity: [
                   '00000001'
                 ],
                 tag: [
                   'preferred_device'
                 ]
               )

puts notification.sid
```

```bash
# Install the twilio-cli from https://twil.io/cli

twilio api:notify:v1:services:notifications:create \
   --service-sid ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \
   --body "Hello Bob" \
   --identity 00000001 \
   --tag preferred_device
```

```bash
curl -X POST "https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Notifications" \
--data-urlencode "Body=Hello Bob" \
--data-urlencode "Identity=00000001" \
--data-urlencode "Tag=preferred_device" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
```

```json
{
  "sid": "NTb8021351170b4e1286adaac3fdd6d082",
  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "date_created": "2016-03-24T23:42:28Z",
  "identities": [
    "jing"
  ],
  "tags": [],
  "segments": [],
  "priority": "high",
  "ttl": 2419200,
  "title": "test",
  "body": "Hello Bob",
  "sound": null,
  "action": null,
  "data": null,
  "apn": null,
  "fcm": null,
  "gcm": null,
  "sms": null,
  "facebook_messenger": null,
  "alexa": null
}
```

> \[!WARNING]
>
> It is best practice, and also potentially required by law in certain
> jurisdictions, for you to have consent from your end users before sending
> messages to them, and you should respect your end users' choice to not receive
> messages from you. It is also important to make sure your database is up to
> date. This is particularly important for number-based communications like SMS
> because over time phone numbers may be reassigned to different individuals. If
> your database is out of date, you could inadvertently send a message to
> someone who did not consent but was reassigned a phone number that was
> previously subscribed to your service by another person. Check out the [Twilio
> Marketplace for Add-ons](/docs/marketplace) from our partners that can help
> you keep your database up to date.\ *Twilio recommends that you consult with
> your legal counsel to make sure that you are complying with all applicable
> laws in connection with communications you transmit using Twilio.*

## Notifications on iOS

***

In this section, we will review how to receive notifications with an iOS device and go through different scenarios of receiving notifications like **App in the Background**, **App in the Foreground** or using **apn payload to display a badge**.

## Receiving Notifications on iOS

iOS has a native listener functions that fire whenever a notification is received. This happens in our **AppDelegate**.

Receiving a Notification in iOS

```objective-c
-(void) application:(UIApplication *) application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo {
  NSLog(@"The notification message is: %@", [userInfo valueForKeyPath:@"aps.alert"]);
}
```

```swift
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
  let message = userInfo["aps"]?["alert"] as? String
  println(message)
}
```

## iOS Notification Scenarios

There are a number of ways we can potentially receive a notification depending on the state of our app, our device type and channel-specific payload specified in notifications. Let's take a look at some of these scenarios.

### App is in the Background

* If it's an alert notification, it will show on the home screen and in the notification center. The notification can be retrieved by parsing the launch options dictionary in **application:willFinishLaunchingWithOptions:** and **application:didFinishLaunchingWithOptions**
* If it's a silent notification, it will be delivered to **application:didReceiveRemoteNotification:fetchCompletionHandler:** and no alert will be raised

### App is in the Foreground

When your app is in the foreground, the message is not shown in the device's notification center; instead, it is delivered to your app and needs to be processed. The app may stay in foreground mode for up to 10 minutes after switching to another application.

* The **application:didReceiveRemoteNotification:fetchCompletionHandler:** method is called but no alert will be raised.

### Displaying a badge

To send a notification to an iOS device displaying a badge, you need to use apn payload.

![Twilio Notify app icon with a red badge showing number 1.](https://docs-resources.prod.twilio.com/400db6c628e12325ae327608ef1d3f3564c0f64e2a179cf027b41c3c1eeeaf8f.png)

Notifications resource has **channel specific parameters (payload)** where you can specify information on how the user should be notified of a Push Notification, including displaying a badge on the app icon. To do that, just add `"badge" : X` (X being the number the app icon will be badged with).

Send a Detailed Notification with Badge

```js
// Download the helper library from https://www.twilio.com/docs/node/install
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

async function createNotification() {
  const notification = await client.notify.v1
    .services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
    .notifications.create({
      apn: {
        aps: {
          alert: {
            title: "Bob alert",
            body: "Bob, you just received a badge",
          },
          badge: 1,
        },
      },
      identity: ["00000001"],
    });

  console.log(notification.sid);
}

createNotification();
```

```python
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)

notification = client.notify.v1.services(
    "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
).notifications.create(
    apn={
        "aps": {
            "alert": {
                "title": "Bob alert",
                "body": "Bob, you just received a badge",
            },
            "badge": 1,
        }
    },
    identity=["00000001"],
)

print(notification.sid)
```

```csharp
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Notify.V1.Service;
using System.Threading.Tasks;
using System.Collections.Generic;

class Program {
    public static async Task Main(string[] args) {
        // Find your Account SID and Auth Token at twilio.com/console
        // and set the environment variables. See http://twil.io/secure
        string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var notification = await NotificationResource.CreateAsync(
            apn: new Dictionary<
                string,
                Object>() { { "aps", new Dictionary<string, Object>() { { "alert", new Dictionary<string, Object>() { { "title", "Bob alert" }, { "body", "Bob, you just received a badge" } } }, { "badge", 1 } } } },
            identity: new List<string> { "00000001" },
            pathServiceSid: "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");

        Console.WriteLine(notification.Sid);
    }
}
```

```java
// Install the Java helper library from twilio.com/docs/java/install

import java.util.Arrays;
import java.util.HashMap;
import com.twilio.Twilio;
import com.twilio.rest.notify.v1.service.Notification;

public class Example {
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
    public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        Notification notification = Notification.creator("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                                        .setApn(new HashMap<String, Object>() {
                                            {
                                                put("aps", new HashMap<String, Object>() {
                                                    {
                                                        put("alert", new HashMap<String, Object>() {
                                                            {
                                                                put("title", "Bob alert");
                                                                put("body", "Bob, you just received a badge");
                                                            }
                                                        });
                                                        put("badge", 1);
                                                    }
                                                });
                                            }
                                        })
                                        .setIdentity(Arrays.asList("00000001"))
                                        .create();

        System.out.println(notification.getSid());
    }
}
```

```go
// Download the helper library from https://www.twilio.com/docs/go/install
package main

import (
	"fmt"
	"github.com/twilio/twilio-go"
	notify "github.com/twilio/twilio-go/rest/notify/v1"
	"os"
)

func main() {
	// Find your Account SID and Auth Token at twilio.com/console
	// and set the environment variables. See http://twil.io/secure
	// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
	client := twilio.NewRestClient()

	params := &notify.CreateNotificationParams{}
	params.SetApn(map[string]interface{}{
		"aps": map[string]interface{}{
			"alert": map[string]interface{}{
				"title": "Bob alert",
				"body":  "Bob, you just received a badge",
			},
			"badge": 1,
		},
	})
	params.SetIdentity([]string{
		"00000001",
	})

	resp, err := client.NotifyV1.CreateNotification("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
		params)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		if resp.Sid != nil {
			fmt.Println(*resp.Sid)
		} else {
			fmt.Println(resp.Sid)
		}
	}
}
```

```php
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "/path/to/vendor/autoload.php";

use Twilio\Rest\Client;

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = getenv("TWILIO_ACCOUNT_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);

$notification = $twilio->notify->v1
    ->services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
    ->notifications->create([
        "apn" => [
            "aps" => [
                "alert" => [
                    "title" => "Bob alert",
                    "body" => "Bob, you just received a badge",
                ],
                "badge" => 1,
            ],
        ],
        "identity" => ["00000001"],
    ]);

print $notification->sid;
```

```ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'twilio-ruby'

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)

notification = @client
               .notify
               .v1
               .services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
               .notifications
               .create(
                 apn: {
                   'aps' => {
                     'alert' => {
                       'title' => 'Bob alert',
                       'body' => 'Bob, you just received a badge'
                     },
                     'badge' => 1
                   }
                 },
                 identity: [
                   '00000001'
                 ]
               )

puts notification.sid
```

```bash
# Install the twilio-cli from https://twil.io/cli

twilio api:notify:v1:services:notifications:create \
   --service-sid ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \
   --apn "{\"aps\":{\"alert\":{\"title\":\"Bob alert\",\"body\":\"Bob, you just received a badge\"},\"badge\":1}}" \
   --identity 00000001
```

```bash
APN_OBJ=$(cat << EOF
{
  "aps": {
    "alert": {
      "title": "Bob alert",
      "body": "Bob, you just received a badge"
    },
    "badge": 1
  }
}
EOF
)
curl -X POST "https://notify.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Notifications" \
--data-urlencode "Apn=$APN_OBJ" \
--data-urlencode "Identity=00000001" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
```

```json
{
  "sid": "NTb8021351170b4e1286adaac3fdd6d082",
  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "date_created": "2016-03-24T23:42:28Z",
  "identities": [
    "jing"
  ],
  "tags": [],
  "segments": [],
  "priority": "high",
  "ttl": 2419200,
  "title": "test",
  "body": "body",
  "sound": null,
  "action": null,
  "data": null,
  "apn": {
    "aps": {
      "alert": {
        "title": "Bob alert",
        "body": "Bob, you just received a badge"
      },
      "badge": 1
    }
  },
  "fcm": null,
  "gcm": null,
  "sms": null,
  "facebook_messenger": null,
  "alexa": null
}
```

**Note**, the device you want to send notifications to has to be registered for receiving Push notifications, including badges. See how to do that in our [Registering for iOS Push Notifications guide](/docs/notify/register-for-notifications-ios)

Now all you need to do is implement badge count, to pass on the correct badge number depending on the logic of your application.

## Notifications on Android

***

In this section, we will review how to receive notifications with an Android device and go through different scenarios of receiving notifications like **App in the Background**, **App in the Foreground**.

## Receiving Notifications on Android

Android has a native listener functions that fire whenever a notification is received. This happens in our **MyFcmListenerService**.

```java title="Receiving a Notification in Android"
private static final String TAG = "MyFcmListenerService";
  @Override
  public void onMessageReceived(RemoteMessage message) {
    Map<String,String> data = message.getData();
    String body = data.get("twi_body");
    String title = data.get("twi_title");
    Log.d(TAG, "From: " + from);
    Log.d(TAG, "Body: " + body);
  }
}

```

The notification will arrive in JSON format and contains the message body as
a String that we can then use locally.

## Android Notifications Scenarios

Now let's see how notifications can be received depending on the state of your app.

### App is in the Background \[#app-is-in-the-background-2]

* Data message (default): If there is only a data bundle then the app is woken up in the background and the **onMessageReceived** function is called. This is the default behavior in Notify as we map all parameters to the data bundle.

> \[!NOTE]
>
> In the [Notification](/docs/notify/api/notification-resource) page, you can
> see how Notification request attributes are mapped to channel-specific
> parameters.

* Notification message: If there is nothing in the data section, then it's added to the notification center.
* Hybrid message: If there is a data section and a notification section, then it is added to the notification center and if the user clicks on the notification then the app is woken up and the data bundle is handed to the **onMessageReceived** function.

#### App is in the Foreground \[#app-is-in-the-foreground-2]

The notification is delivered to **onMessageReceived** of the **FcmListenerService**. The data key-value pairs can be found in the data bundle, but the key-value pairs of the notification bundle are not available.

## What's next

***

To get a more in-depth look at the Notifications resources check out our [REST API Guide](/docs/notify/api).
