Notifications

In this document, you can learn how to send notifications in apps.

Sending Notifications

To send notifications from your app, requires four steps, these are:

  1. Fetch the notification manager from the server.

  2. Use the notification manager to create a notification object.

  3. Set the notification’s information

  4. Send the notification.

You can see an example of how to perform all of these steps in the example below. The notification has a number of properties set that help identify the app that should receive it, along with information for the receiving app to use, once the notification has been received.

<?php

/** @var \OCP\Notification\INotification $notification */
$notification = $this->notificationManager->createNotification();

// Populate the notification object
$notification
    ->setApp('customgroups')
    ->setDateTime(new \DateTime())
    ->setObject(
        'customgroup',
        $memberInfo['group_id']
    )
    ->setSubject(
        'changed_member_role',
        [
            $user->getDisplayName(),
            $groupInfo['display_name'],
            $memberInfo['role']
        ]
    )
    ->setMessage(
        'changed_member_role',
        [
            $user->getDisplayName(),
            $groupInfo['display_name'],
            $memberInfo['role']
        ]
    )
    ->setUser($targetUserId)
    ->setLink($link);

// Send the notification
$this->notificationManager->notify($notification);
Make sure the app set in the notification matches the one you’re expecting, because other notifications for other apps might reach your notifier. Throw an InvalidArgumentException if this isn’t the case.
The notification’s subject and message should be set using translated strings.

In case you need to add some actions to the notification (e.g., to accept or reject shares, or other kind of actions):

  1. Create the action from the notification

  2. Fill the action data

  3. Add the action in the notification

You can see an example of how to perform all of these steps in the example below.

<?php

/** @var \OCP\Notification\INotification $notification */
$notification = $this->notificationManager->createNotification();
$action = $notification->createAction();
$action->setLabel(....)
    ->setLink(...)
$notification->setApp('customgroups')
    ->setDateTime(new \DateTime())
    ->setObject(
        'customgroup',
        $memberInfo['group_id']
    )
    ->setSubject(
        'changed_member_role',
        [
            $user->getDisplayName(),
            $groupInfo['display_name'],
            $memberInfo['role']
        ]
    )
    ->setMessage(
        'changed_member_role',
        [
            $user->getDisplayName(),
            $groupInfo['display_name'],
            $memberInfo['role']
        ]
    )
    ->setUser($targetUserId)
    ->setLink($link)
    ->addAction($action);
$this->notificationManager->notify($notification);