• Stars
    star
    245
  • Rank 165,304 (Top 4 %)
  • Language
    Java
  • Created almost 9 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Android system notifications for React Native. Supports push notifications with GCM integrated.

[WARNING: NOT MAINTAINED] Android system notifications for React Native. Supports push notifications with GCM integrated. Another push-notification solution on Android is https://github.com/zo0r/react-native-push-notification, it features on providing the same API on iOS and Android, while this one supports more notification features on Android.

react-native-system-notification npm version

Send or schedule Android system notifications for React Native.

Table of Contents


import React, { DeviceEventEmitter } from 'react-native';
import Notification from 'react-native-system-notification';

// Send a simple notification
Notification.create({ subject: 'Hey', message: 'Yo! Hello world.' });

// Listen to notification-clicking events
Notification.addListener('press', function(e) {
  console.log(e);
});

// Custom payload for notifications
Notification.create({
  subject: 'Notification With Payload',
  message: 'This is a notification that contains custom payload.',
  payload: { number: 1, what: true, someAnswer: '42' }
});

// Receive the payload on notification events
Notification.addListener('press', function(e) {
  console.log(e.payload);  // => { number: 1, what: true, someAnswer: '42' }
});

// Customize notification
Notification.create({
  subject: 'Notification With Custom Icon',
  message: 'This is a notification with a specified icon.',
  smallIcon: 'ic_alert'
});

// Scheduled notifications
Notification.create({
  subject: 'Scheduled Notification',
  message: 'This notification will show on every Friday morning at 8:30 AM, starts at 2015/9/9 and end after 10 times.',
  sendAt: new Date(2015, 9, 9, 8, 30),
  repeatEvery: 'week',
  count: 10
});

Installation

  • Run npm install react-native-system-notification --save to install using npm.

  • Add the following two lines to android/settings.gradle:

include ':react-native-system-notification'
project(':react-native-system-notification').projectDir = new File(settingsDir, '../node_modules/react-native-system-notification/android')
  • Edit android/app/build.gradle and add the annoated lines as below:
...

dependencies {
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:0.16.+"
    compile project(':react-native-system-notification')  // <- Add this line
}
  • Edit android/app/src/main/AndroidManifest.xml and add the annoated lines as below:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.reactnativeproject">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_TASKS" />                       <!-- <- Add this line -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>           <!-- <- Add this line -->
    <uses-permission android:name="android.permission.VIBRATE"/>                          <!-- <- Add this line -->

    <application
      android:allowBackup="true"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:theme="@style/AppTheme">

...

      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
      <receiver android:name="io.neson.react.notification.NotificationEventReceiver" />   <!-- <- Add this line -->
      <receiver android:name="io.neson.react.notification.NotificationPublisher" />       <!-- <- Add this line -->
      <receiver android:name="io.neson.react.notification.SystemBootEventReceiver">       <!-- <- Add this line -->
        <intent-filter>                                                                   <!-- <- Add this line -->
          <action android:name="android.intent.action.BOOT_COMPLETED"></action>           <!-- <- Add this line -->
        </intent-filter>                                                                  <!-- <- Add this line -->
      </receiver>                                                                         <!-- <- Add this line -->
    </application>

</manifest>

The RECEIVE_BOOT_COMPLETED permission is used to re-register all scheduled notifications after reboot. Requesting VIBRATE permission is required if you want to make the device vibrate while sending notifications.

  • Edit MainActivity.java (usually at android/app/src/main/java/com/<project-name>/MainActivity.java) and add the annoated lines as below:
...

import android.content.Intent;
import android.os.Bundle;

import com.facebook.react.ReactActivity;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;

import io.neson.react.notification.NotificationPackage;    // <- Add this line

public class MainApplication extends Application implements ReactApplication {

...

    @Override
    protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
            ...
            new NotificationPackage()                  // <- Add this line
        );
    }

...

Usage

Creating Notifications

Just do:

Notification.create({
  id: 1337,
  subject: 'Notification With Payload',
  message: 'This is a notification that contains custom payload.',
  smallIcon: 'ic_launcher',
  autoClear: true,
  payload: { number: 1, what: true, someAnswer: '42' }
});

All functions of this module will return promises with the notification object handing in. So you can get the data of the notification and do anything that is needed, like this:

Notification.create({ message: 'Testing.' }).then(function(notification) {
  console.log(notification);
  console.log(notification.id);
});

All available options on a notification are listed below:

Basic

id (number) The unique ID of this notification. It will be randomly chosen if not specified.

subject (string) The notification subject. Defaults to the application name on Android.

message (string) The message showen in the notification.

action (string) An action name that can be used to determine what to do when this notification is clicked. Defaults to DEFAULT.

payload (object) A custom payload object. It can be retrieved on events of this notification. Defaults to {}.

Scheduling

delay (number) Milliseconds to delay before showing this notification after it is created. Useful when creating countdown alarms, reminders, etc. Note that it cannot be used with sendAt.

sendAt (Date) Schedule this notification to show on a specified time. Note that it cannot be used with delay.

repeatEvery (string or number) Must use with sendAt. Schedule this notification to repeat. Can be minute, hour, halfDay, day, week, month, year or a number of time in milliseconds.

repeatCount (number) Must use with sendAt and repeatEvery. End repeating this notification after n times. Note that it cannot be used with endAt.

endAt (Date) Must use with sendAt and repeatEvery. End repeating this notification after a specified time. Note that it cannot be used with repeatCount.

Some Samples of Scheduled Notifications

Notification.create({
  subject: 'Scheduled Notification',
  message: 'This notification will show on every Friday morning at 8:30 AM, starts at 2015/9/9 and end after 10 times.',
  sendAt: new Date(2015, 9, 9, 8, 30),
  repeatEvery: 'week',
  repeatCount: 10
});
Notification.create({
  subject: 'Scheduled Notification',
  message: 'This notification will show on 2015/9/9 morning at 8:30 AM, and repeat for 10 times every minute.',
  sendAt: new Date(2015, 9, 9, 8, 30),
  repeatEvery: 60000,
  repeatCount: 10
});
Notification.create({
  subject: 'Delayed Notification',
  message: 'This notification will show after 10 seconds, even the app has been stoped.',
  delay: 10000
});

Customization

priority (number) Priority of this notification, can be -2, -1, 0, 1, 2. When this is set to 1 or 2, heads-up notification will be more likely to show on Android 5+. Defaults to 1.

smallIcon (string) The icon (file name) to show. This icon must be placed in the project's android/app/src/main/res/mipmap-* folder. Defaults to ic_launcher.

largeIcon (string) Not yet implemented.

sound (string) Set the sound to play. Defaults to default as using the default notification sound, or set this to null to disable the sound. Other options are not yet implemented.

vibrate (string) Set the vibration pattern to use. Defaults to default as using the default notification vibrate, or set this to null to disable the vibrate. Other options are not yet implemented.

lights (string) Set the desired color for the indicator LED on the device. Defaults to default as using the default notification lights, or set this to null to disable the lights. Other options are not yet implemented.

autoClear (boolean) Clear this notification automatically after the user clicks on it. Defaults to true.

onlyAlertOnce (boolean) Do not let the sound, vibrate and ticker to be played if the notification is already showing.

tickerText (string) Set the text to show on ticker. Defaults to <subject>: <message>. Set this to null to disable ticker.

when (Date) Add a timestamp pertaining to the notification (usually the time the event occurred).

bigText (string) Set the text to be shown when the user expand the notification.

bigStyleImageBase64 (string) Set the image in base64 to be shown when the user expand the notification. if bigText is not null, it have priority over bigStyleImageBase64.

bigStyleUrlImgage (string)
Set URL of a image. Geting it by open a stream connection and it be shown when the user expand the notification.. if bigText is not null, it have priority over bigStyleUrlImgage

subText (string) Set the third line of text in the platform notification template. Note that it cannot be used with progress.

progress (number) Set the progress this notification represents, range: 0.0 ~ 1.0. Set this to a number lower then zero to get an indeterminate progress. Note that it cannot be used with subText.

color (string) Color to be applied by the standard Style templates when presenting this notification.

number (number) Set a number on the notification.

private (boolean) Not yet implemented.

ongoing (boolean) Not yet implemented.

category (string) Set the notification category, e.g.: alarm, call, email, event, progress, reminder, social. It may be used by the Android system for ranking and filtering.

localOnly (boolean) Set whether or not this notification should not bridge to other devices.

Handle Notification Click Event

Register a listener on sysNotificationClick events to handle notification clicking:

Notification.addListener('press', function(e) {
  console.log(e);
});

The action and payload of the notification can be retrieved on these events:

Notification.send({ message: 'Message', action: 'ACTION_NAME', payload: { data: 'Anything' } });
Notification.addListener('press', function(e) {
  switch (e.action) {
    case 'ACTION_NAME':
      console.log(`Action Triggered! Data: ${e.payload.data}`);
      break;

    case 'ANOTHER_ACTION_NAME':
      console.log(`Another Action Triggered! Data: ${e.payload.data}`);
      break;
  }
});

Once you no longer need to listen to sysNotificationClick events de-register the listener functions with:

Notification.removeAllListeners('press');

Manage Scheduled Notifications

Sometimes you'll need to get the scheduled notifications (which has delay or sendAt set up) that you had created before. You can use Notification.getIDs() to retrieve an array of IDs of available (i.e. will be send in the future) scheduled notifications.

Notification.getIDs().then(function(ids) {
  console.log(ids);  // Array of ids
});

and use Notification.find(notificationID) to get data of an notification.

Notification.find(notificationID).then(function(notification) {
  console.log(notification);
});

or just cancel it with Notification.delete(notificationID):

Notification.delete(notificationID);

Want to cancel all scheduled notifications set by your app? Sure:

Notification.deleteAll();

To update a scheduled notification, just use Notification.create() with the same id.

Clearing Notifications

When you want to clear a notification from the system statusbar, just use:

Notification.clearAll();

or:

Notification.clear(notificationID);

Push Notifications On Android

Sending push notification via web servers to Android is also easy! With react-native-gcm-android intergrated, you can just pass notification arguments through GCM (with the same format as JavaScript), your app will show it directly or put it into schedule. To set this up, follow these directions:

  1. Run npm install react-native-gcm-android --save to add react-native-gcm-android to your app

  2. Setup GCM, follow react-native-gcm-android's README to get GCM working.

  3. Open android/app/src/main/AndroidManifest.xml, change com.oney.gcm.RNGcmListenerService to io.neson.react.notification.GCMNotificationListenerService.

Then you can send push notifications like this, putting an notification object (just as the same thing that you use in JavaScript Notification.create()) into the GCM data (curl example):

curl -X POST -H "Authorization: key=<your_google_api_key>" -H "Content-Type: application/json" -d '
{
  "data": {
    "notification": {
      "subject": "Hello GCM",
      "message": "Hello from the server side!"
    }
  },
  "to" : "<device_token>"
}' 'https://gcm-http.googleapis.com/gcm/send'

The notification will be created natively (so this works even if the app is closed) when the device received the GCM message.

More Repositories

1

LLaMA-LoRA-Tuner

UI tool for fine-tuning and testing your own LoRA models base on LLaMA, GPT-J and more. One-click run on Google Colab. + A Gradio ChatGPT-like Chat UI to demonstrate your language models.
Python
432
star
2

Inventory

An RFID asset management app for home or businesses.
TypeScript
148
star
3

alfred-google-translate-workflow

Alfred Google Translate Workflow. Alfred 多語言翻譯 Workflow,含有拼字校正、近似詞建議功能。(Temporally broken, use https://github.com/zetavg/alfred-google-translate-workflow/pull/8)
JavaScript
88
star
4

react-native-android-design-support

[WARNING: NOT MAINTAINED] React Native wrapper for Android Design Support Library, providing Material Design to modern and also older Android devices.
Java
28
star
5

twlm

Taiwanese Mandarin LLM Project
Python
19
star
6

dotfiles

Dotfiles. Mac and *nix. Handy scripts, configurations for bash, zsh, git, asdf, Sublime Text, Karabiner-Elements, BetterTouchTool and more.
HTML
18
star
7

graphql-todomvc

TodoMVC demonstration of Relay / GraphQL
JavaScript
16
star
8

RailsRelayTodoMVC

TodoMVC demonstration of Rails + GraphQL + Relay
JavaScript
14
star
9

Flying-Wings

《飛ぶの翼》– Unity 立體機動裝置遊戲。完整實作出來的部分著重於操控方式的設計。 (NTUST 2013 Fall Mobile Game Design — Second Place) #進擊的巨人 #米卡莎
Java
11
star
10

api_helper

Helpers for creating standard RESTful API for Rails or Grape with Active Record.
Ruby
11
star
11

date-parser

將口語的日期時間解析成 Date 物件。
CoffeeScript
10
star
12

nix-packages

Nix packages. Ruby, Rails, Node.js/NPM, Passenger w/ Nginx.
Nix
10
star
13

chrome-devtools-hack

Hacks for Google Chrome DevTools.
JavaScript
10
star
14

RaffleDraw

3D 抽獎機
JavaScript
10
star
15

Vertical-External-Monitor-Mount-for-Laptop

Mount an external monitor on top of your laptop's built-in monitor—benefits your digital nomad experience and your neck.
9
star
16

alfred-new-arc-window-workflow

Open a new Arc browser window for a specific workspace.
JavaScript
7
star
17

opsworks_cookbooks

A collection of useful cookbooks for AWS OpsWorks.
Ruby
7
star
18

TaskSync

我只是想在同一個地方看到今天該做的事。
JavaScript
6
star
19

nix-hello-world

Hello world program to experience on Nix derivation/packages.
Nix
6
star
20

Feedify

Full-text RSS feeds
JavaScript
6
star
21

NTUvote-UI

台大電子投票前端介面
CSS
6
star
22

avatorGen

泛用型頭像產生器,可用於特定活動或事件,快速做出大頭貼製造機。
CSS
6
star
23

chrome-extension-icons-patch

Yet another sign of wasted life.
Ruby
5
star
24

RailsRelayReact3

Rails - Relay - React 實驗專案 3 (論壇) 注意:此 repo 為了維持 commit log 好閱讀,若有修改過去內容,會使用 rebase 然後 force push 來更新。
JavaScript
5
star
25

react-native-google-analytics-native

Native Google Analytics for React Native. Using the Universal Analytics SDK, you can get native-level details (that are not accessible by JavaScript) while receiving analytics data, e.g.: device brand, screen resolution, OS version and more.
Java
4
star
26

spacegray-input-vscode

The Spacegray theme with the Input font for VSCode.
CSS
4
star
27

nixos-configs

My NixOS configurations.
Nix
3
star
28

TripBook

大概可以暫時稱之為一個讓深度共通脈絡得以存在的社交平台。
Ruby
3
star
29

llm_assistant_bot

(WIP) LLM powered Slack Bot for assisting you and your team.
Python
3
star
30

dotfiles_old_2015

My dotfiles
Shell
3
star
31

QtReversi

黑白棋遊戲
C
2
star
32

BentOS

The Bento Operation System.
Ruby
2
star
33

redmine_home_activities

A Redmine plugin that displays latest activities on home page, just like Github.
Ruby
2
star
34

twlm-demo

A demo UI of TW Pythia (https://github.com/zetavg/twlm) based on https://github.com/zetavg/LLaMA-LoRA-Tuner.
Python
2
star
35

MISK-Hubot

MISK 內部聊天室機器人,幫助我們處理各種通知提醒、服務運營狀態監控、專案進度回報、任務追殺以及提供各種聊天室小工具。
CoffeeScript
2
star
36

web_task_runner

A web task runner framework in Ruby.
Ruby
2
star
37

LLM-Research

Colab notebooks and experimental code related to personal research on Large Language Models.
Jupyter Notebook
2
star
38

generate-build-results-md-action

TypeScript
2
star
39

yarn-workspaces-list-action

This GitHub action lists all Yarn (v2+) Workspace packages that match a specific condition.
2
star
40

ai-assistant-tools

JavaScript
1
star
41

Exercism

My exercism.io solutions.
Haskell
1
star
42

ColorgyTry01

JavaScript
1
star
43

dotfiles-old-2017

Shell
1
star
44

electric_lock_control_esp8266

Use ESP8266 to to control traditional electronic door locks which are popular in apartments across Taiwan.
C++
1
star
45

mvcss-scss

MVCSS in SCSS format.
CSS
1
star
46

google-functions-nodejs-template

A template for writing Google Cloud Function with Node.js, TypeScript, Babel, ESLint, and Prettier.
TypeScript
1
star
47

typescript-presentation-playground

JavaScript
1
star
48

npm-nix-sample

Nix
1
star
49

stanford-algorithms-programming-assignments

C++
1
star
50

vivaldi-patch

Patches for the Vivaldi browser.
JavaScript
1
star
51

htt

Read and manage offline websites easily.
JavaScript
1
star
52

unofficial-medium-api

JavaScript
1
star
53

hello-firebase

Firebase project template using TypeScript, Babel, ESLint, and Prettier. Includes "configuration as code" management, one-click deployment to Firebase, and one-click running the whole stack on local. See branches for a React web app (based on CRA) and Telegram bot (using telegraf) sample, both include one-click deployment using Firebase Hosting or Cloud Functions.
JavaScript
1
star
54

rails-nix-sample

Minimum Rails app packaged by Nix
Nix
1
star
55

AuthProvider

OAuth 2 compatible mobile authentication provider for Rails.
Ruby
1
star
56

create-react-app-radix-tailwind-typescript-template

Create React App with TypeScript, Tailwind, and Radix UI (with shadcn/ui). With the help of CRACO (Create React App Configuration Override), ESLint, Prettier, simple-import-sort, Jest and absolute imports with @/*.
TypeScript
1
star
57

generate-build-notes-action

JavaScript
1
star