How to Push Local Notification With React Native

This post is written by my good friend Aviad Holy who’s a team leader at Checkmarx and an Android enthusiast.

Installation and linking

Prerequisites

To see React Native live without installing anything check out Snack.

With my current setup (Windows 10 64 bit and Android phone)

  • I installed all prerequisites above
  • Started development server
C:\Users\xyz\AppData\Roaming>cd AwesomeProject

C:\Users\xyz\AppData\Roaming\AwesomeProject>yarn start
yarn run v1.22.10
  • Scanned QR Code shown in the development server
  • And I saw app started on my Android phone

Now you’re ready to follow Aviad’s tutorial below

I was looking for a simple solution to generate a local push notification in one of my projects,  when I came across this wonderful package that does exactly what is need and suitable for both iOS and Android, https://github.com/zo0r/react-native-push-notification.

The package has pretty good documentation, with only minor things missing to make it work straightforward. In the following guide I will present the configuration required and a suggested implementation to get you start pushing notifications locally. 

This guide targets Android since I encounter a lot of questions around it.

  • pending on your requests a dedicated guide for ios may be published as well.

Installation and linking, the short story.

  • yarn add react-native-push-notification
  • android/build.gradle
ext {
        buildToolsVersion = "29.0.3"
        minSdkVersion = 21
        compileSdkVersion = 29
        targetSdkVersion = 29
        ndkVersion = "20.1.5948944"
        googlePlayServicesVersion = "+" // default: "+"
        firebaseMessagingVersion = "+" // default: "+"
        supportLibVersion = "23.1.1" // default: 23.1.1
    }
  • android/app/src/main/AndroidManifest.xml
<span class="has-inline-color has-black-color">...
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
...
<application
...>
<meta-data  android:name="com.dieam.reactnativepushnotification.notification_foreground"
    android:value="false"/>
      <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
          android:resource="@color/white"/>
      <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
      <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
      <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
        <intent-filter>
          <action android:name="android.intent.action.BOOT_COMPLETED" />
          <action android:name="android.intent.action.QUICKBOOT_POWERON" />
          <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
        </intent-filter>
      </receiver>
...
</application></span>


  • create /app/src/main/res/values/colors.xml
<span class="has-inline-color has-black-color"><resources>
    <color name='white'>#FFF</color>
</resources></span>


  • android/settings.gradle
include ':react-native-push-notification'
project(':react-native-push-notification').projectDir = file('../node_modules/react-native-push-notification/android')
  • android/app/build.gradle
dependencies {
...
    implementation project(':react-native-push-notification')
...
}

Usage

  • create a new file src/handlers/notificationsInit.js to initialize our push notification

Pay attention that for Android, creating a notification channel and setting the request permission as  “iOS only” is a must, as presented in the following example.

<span class="has-inline-color has-black-color">import PushNotification from 'react-native-push-notification';
import { Platform } from 'react-native';
 
export const notificationsInit = () => {
    PushNotification.createChannel({
        channelId: 'channel-id-1',
        channelName: 'channel-name-1',
        playSound: true,
        soundName: 'default',
        importance: 4,
        vibrate: true,
    }, (created) => colnsloe.log(`createChannel returned '${created}'`)
    );
    PushNotification.configure({
        onRegister: function (token) {
            console.log('TOKEN:', token);
        },
        onNotification: function (notification) {
            console.log('NOTIFICATION:', notification);
        },
        permissions: {
            alert: true,
            badge: true,
            sound: true,
        },
        requestPermissions: Platform.OS === 'ios',
        popInitialNotification: true,
    });
}</span>


  • create a new file src/handlers/notifications.js
<span class="has-inline-color has-black-color">import PushNotification from 'react-native-push-notification';
 
export const showNotification = (title, message) => {
    PushNotification.localNotification({
        channelId: 'channel-id-1',
        title: title,
        message: message,
    })
}
export const showScheduleNotification = (title, message) => {
    PushNotification.localNotificationSchedule({
        channelId: 'channel-id-1',
        title: title,
        message: message,
        date: new Date(Date.now() + 3 * 1000),
        allowWhileIdle: true, 
    })
}
export const handleNotificationCancel = () => {
    PushNotification.cancelAllLocalNotifications();
}
</span>

  • Import and initialize notificationsInit in App.js
<span class="has-inline-color has-black-color">import React from 'react';
import { View } from 'react-native';
import { notificationsInit } from './src/handlers/notificationsInit';
 
const App = () => {
 
  notificationsInit;
 
  return (
      <View>
      </View>
  );
};
 
export default App;</span>


  • Now, lets display the notification
  • create a new file src/components/TestNotifications.js
<span class="has-inline-color has-black-color">import React from 'react';
import { View, TouchableOpacity, StyleSheet, Text } from 'react-native';
import {
    showNotification,
    showScheduleNotification,
    handleNotificationCancel
} from '../handlers/notifications';
 
export default class TestNotifications extends React.Component {
 
    onTriggerPressHandle = () => {
        showNotification('Simple notification', 'simple notification triggered, nice work');
        console.log('simple notification triggered');
    }
 
    onSchedulePressHandle = () => {
        console.log('schedule notification triggered');
        showScheduleNotification('Schedualed notification', 'Schedualed notification triggered, nice work');
    }
 
    onCancelHandle = () => {
        handleNotificationCancel();
        console.log('cancel notification triggered');
    }
 
    render() {
        return (
            <View>
                <Text style={styles.title}>Click to try</Text>
                <TouchableOpacity
                    style={styles.button}
                    onPress={this.onTriggerPressHandle}>
                    <Text style={styles.text}>Simple notification</Text>
                </TouchableOpacity>
                <TouchableOpacity
                    style={styles.button}
                    onPress={this.onSchedulePressHandle}>
                    <Text style={styles.text}>{'--Scheduled notification--\nFire in 3 secondes'}</Text>
                </TouchableOpacity>
                <TouchableOpacity
                    style={[styles.button, {backgroundColor: 'red'}]}
                    onPress={this.onCancelHandle}>
                    <Text style={styles.text}>Cancel all notification</Text>
                </TouchableOpacity>
            </View>
        );
    }
}
 
const styles = StyleSheet.create({
    button: {
        backgroundColor: 'dodgerblue',
        height: 80,
        borderRadius: 10,
        margin: 20,
        justifyContent: 'center'
    },
    text: {
        color: 'white',
        textAlign: 'center',
        fontSize: 20,
    },
    title: {
        backgroundColor:'dimgrey',
        color: 'white',</span>
        <span class="has-inline-color has-black-color">textAlign: 'center',
        textAlignVertical: 'center',
        fontSize: 30,
        height: 100,
        marginBottom: 20,
    }
});</span>


  • import TestNotifications component to App.js
<span class="has-inline-color has-black-color">import React from 'react';
import TestNotifications from './src/components/TestNotifications';
import { View } from 'react-native';
import { notificationsInit } from './src/handlers/notificationsInit';
 
const App = () => {
 
  notificationsInit;
 
  return (
      <View>
        <TestNotifications />
      </View>
  );
};
 
export default App;</span>


Try out the buttons to trigger the notifications

Feel free to clone and play with this project sample

https://github.com/aviadh314/RN-local-push-notification.git

Java Code Geeks
Web Code Geeks

Books About Space. We Have A Liftoff!

Photo by SpaceX on Unsplash

This post continues the series of posts describing books I read end-to-end and classified in accordance with some criteria. This time we are talking about books on space and space exploration. You may also check related posts: this, this, this, and this, I wrote previously.

Aviation Books Classified

As I mentioned previously, this post is about organizing the books I read about aviation in a particular structure that could be useful to other readers. This post is based partially on the post I wrote about the origins of Stealth technology and the post on aviation related books in general. In short, my classification is about civil and military aviation with some sub-categories inside each branch of aviation.

Aviation

  • Civil Aviation
    • Biographies of plane engineers
      • 747 by Joe Sutter. This book could be of interest to people who not only want to learn about the 747, but also want to know who developed it, why and how it happened. Joe Sutter produced an interesting nerative that is fun to read.
    • Biographies of jet engine engineers
      • The Power to Fly: An Engineer’s Life by Brian H. Rowe. This book provides you with an information of how jet engines were developed in General Electric Engines and also provides you with author’s personal advice on engineering and management.
      • Herman the German: Just Lucky I Guess by Gerhard Neumann. While I read the book by Brian H. Rowe he mentioned that his boss at GE Aviation Engines was Gerhard Neumann who was quite a personality. I was curious so I bought this book. It was very adventurous reading to say the least. It seems like Gerhard Neumann had the most adventurous life of any person on earth. Surely, more adventurous, than Indiana Jones could ever dream of.
  • Military Aviation
    • Jet Fighter Planes
      • Hornet: The inside Story of The F/A-18 by Orr Kelly. This books provides many details of how F/A-18 was conceived, designed and developed. I was very impressed with the book, taking into consideration, that at first I thought about F/A-18 as an ugly plane.
    • Biographies of military jet planes engineers
      • Kelly: More Than My Share of It All by Kelly Johnson. Well, I guess there is no need to introduce who Kelly Johnson was. And if there is a need to do this, then he’s the father of Skunk Works which brought you U-2, A-12, SR-71 and other Area 51 planes.
      • Skunk Works: A Personal Memoir of My Years of Lockheed by Ben Rich. This book is very exciting and it talks about F-117 design and development also touching on SR-71 and other planes developed by Skunk Works. Ben Rich started as a thermodynamics specialist of SR-71 in Kelly Johnson team, later to succeed him as Skunk Works director. By the way, his son Michael D. Rich is the CEO of RAND corporation.
    • Low Observable Technology aka Stealth

The Book Struggle Within

This is a story of struggle, love and hate, but it’s not a movie. Instead, it’s a post about my love-hate relationship with digital versus print books. I think readers who like reading both print and e-books could understand what I am talking about. There is a constant tension, even a fight, between each book type and the pros and cons they have. I personally tend to read print books, though when it’s dark and there is no good lighting available there is nothing like reading an e-book.

Well, that’s the main point, these two kinds of books are not contradictory, but could be viewed as a complementary solutions. Each type has its advantages and disadvantages, but when combining advantages of both print and e-books we got the best out of all worlds.

Print books advantages as I see them

As biological agents living in a physical world we tend to like things that we can touch, hold and feel. So it’s not a big surprise that physical print books are so appealing to us. The book having a good and colorful cover draws attention and has a seductive forces to it. You can take it, flip through it quickly. Check whether are there any good diagrams, or pictures. Jump to the end of the book to check how it ends. In addition, the books have a smell to them and their weight provides a reassurance that knowledge could be a real force in the world.

  • I value the most the flipping part and fast navigation through the print books.

Well what are the disadvantages?

Print books, being physical objects take a lot of space, which could be an issue and storing them requires a book shelf or shelves. If you happen to travel or simply wants to take a few books with you to read on the go, then you’d better be in a good physical shape and have a big suitcase, which is kind of problematic to say the least (I mean the suitcase).

Also, print books are usually cost more then their digital counterparts, so buying them isn’t cheap. But both digital and print books could be rented or borrowed in the library making them less expensive as a product.

With a print book you need a good lighting, good weather conditions, preferably without pouring rain, when you outside, and a table with a chair. Non of this is required for digital books, for example, when reading on a mobile phone.

E-books advantages as I see them

E-books are cost effective, take almost no physical space, except for the container where they reside as bytes in memory. Nowadays, they can be read on a dedicated devices, computers, mobile phones. The e-books themselves could be stored locally or read in the cloud. There are a number of good mobile phone applications and dedicated websites that provide a reader with conveniences of reading, searching, translating and highlighting the content of the digital books. When the time comes to move around, you can carry almost unlimited number of e-books, limited by the memory space you have on you device (or a remote server). All in all, the e-books sound like a clear winner in the print versus digital books fight.

  • I value the most reading in the dark, searching and translating capabilities.

But…

E-books disadvantages

Though, e-books could be read in complete darkness, it points out that the device that they are stored in requires electricity, hence a battery that should be charged. When the battery is empty good bye. Nowadays, reading a digital book requires downloading it from a cloud storage locally, which means there is a need in an internet connection, which too could be interrupted. In addition, since digital books are presented in strictly two dimensional format it is impossible to flip through them like could be done with a print book, and jumping back and forth quickly is also hardly possible, if at all. But searching them for a particular word or phrase, or translating content is a charm in comparison to print counterparts (strictly speaking it’s an advantage, ops). In addition, when you try reading and working with the content from a number of books in parallel (which happens to me) all you need is a regular table. To achieve the same feat with an e-book you need a big size monitor, and I mean really big.

Conclusion

Unless there will be invented a hybrid of a print and e-book, that would require almost no electricity (or would have a long lasting battery) and could be flipped in 3D space (say like a hologram), we are destined to use both approaches depending on circumstances where the reading process should take place.

  • One side note I forgot to mention, we have physical books (scrolls) that survived for thousands of years, but our electronic devices that store e-books definitely would not.