• Stars
    star
    173
  • Rank 212,179 (Top 5 %)
  • Language
    Kotlin
  • License
    MIT License
  • Created almost 4 years ago
  • Updated 11 months ago

Reviews

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

Repository Details

📲 Communicate with nearby devices using Bluetooth, BLE, WiFi and near-ultrasonic audio. Broadcast and receive small payloads (like strings) using the easy-to-use React Native API!

react-native-google-nearby-messages

An async Google Nearby Messages API Wrapper for React Native (Android & iOS), supporting autolinking, custom discovery modes (broadcast, scan, ..), custom discovery mediums (bluetooth, audio, ..), awaitable native invokations and React hooks!

Also, this is a good example on how to use Swift in a React Native - Native Module.

react-native-google-nearby-messages GitHub stars GitHub followers

Buy Me a Coffee at ko-fi.com

Install

This packages uses React Native autolinking (> 0.60)

npm i react-native-google-nearby-messages
# for iOS
cd ios && pod install && cd ..

Note (iOS): Everytime you run pod install an entry called Assets.car is created in your Build Phases -> [CP] Copy Pods Resources which causes the build to fail. This is a known bug in the Google NearbyMessages pod. A workaround is to manually remove this file everytime you run pod install. See #4 (comment) for an automatic fix. Please create a PR here if you found a better solution for this!

Usage

See the example app.

iOS Setup

See: https://developers.google.com/nearby/messages/ios/get-started

  1. Add bluetooth permissions (NSBluetoothPeripheralUsageDescription, NSBluetoothAlwaysUsageDescription for 'ble', and NSMicrophoneUsageDescription for 'audio') to Info.plist
  2. Create your API Key at the Google Developer Console.
  3. (Optionally): Add the react-native-permissions library to check if Bluetooth is available on the device (it's 'unavailable' on iOS Simulators!) If it's 'unavailable', calls to subscribe or publish might crash the app (EXC_BAD_ACCESS) so only call if Bluetooth permission is denied, granted or blocked. This library will handle the permission checking for you when you call publish() or subscribe() for the first time.
  4. Pass the generated API Key as a parameter using the connect function

Android Setup

See: https://developers.google.com/nearby/messages/android/get-started

  1. Create your API Key at the Google Developer Console.

  2. Add your generated API Key and Permissions to your AndroidManifest.xml:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.google.sample.app" >
        <!-- For BLE/Bluetooth -->
        <uses-permission android:name="android.permission.BLUETOOTH" />
        <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
        <!-- For Audio -->
        <uses-permission android:name="android.permission.RECORD_AUDIO" />
    
        <application ...>
            <meta-data
                android:name="com.google.android.nearby.messages.API_KEY"
                android:value="API_KEY" />
            <activity>
            ...
            </activity>
        </application>
    </manifest>
  3. (Optionally): Call checkBluetoothAvailability() to ensure that Bluetooth capabilities are available on the current device.

  4. Call connect without any key.

Publishing

import { connect, publish, addOnErrorListener } from 'react-native-google-nearby-messages';

const removeListener = addOnErrorListener((kind, message) => console.error(`${kind}: ${message}`));
const disconnect = await connect({ apiKey: GOOGLE_API_KEY });
const unpublish = await publish('hello !');

// later, e.g. in componentWillUnmount()
removeListener();
unpublish();
disconnect();

Make sure to unpublish, disconnect and remove any listeners as they won't be removed automatically! I don't know if that's possible, if so, please create a Pull Request.

Subscribing

import { connect, subscribe, addOnErrorListener } from 'react-native-google-nearby-messages';

const removeListener = addOnErrorListener((kind, message) => console.error(`${kind}: ${message}`));
const disconnect = await connect({ apiKey: GOOGLE_API_KEY });
const unsubscribe = await subscribe(
  (m) => {
    console.log(`new message found: ${m}`);
  },
  (m) => {
    console.log(`message lost: ${m}`);
  });

// later, e.g. in componentWillUnmount()
removeListener();
unsubscribe();
disconnect();

Make sure to unpublish, disconnect and remove any listeners as they won't be removed automatically! I don't know if that's possible, if so, please create a Pull Request.

Bluetooth Availability

Check if the user has granted Bluetooth Permissions. This feature is experimental, and strongly differs between iOS and Android.

import { checkBluetoothPermission } from 'react-native-google-nearby-messages';

const hasPermission = await checkBluetoothPermission();

Check if bluetooth is available on this device. This feature is experimental, and strongly differs between iOS and Android. Make sure to use a library like react-native-permissions to check if Bluetooth is really available, otherwise your Application might crash with a EXEC_BAD_ACCESS error. See troubleshooting

import { checkBluetoothAvailability } from 'react-native-google-nearby-messages';

const isBluetoothAvailable = await checkBluetoothAvailability();

React Hooks

This library also provides react hooks for common use cases. In case you're not familiar with hooks, please read the hooks documentation. When the component unmounts, the hooks automatically stop publishing, subscribing, remove error listeners and disconnect for you. You can also look into the hooks source code and tweak them for your use case.

Make sure to memoize the NearbyConfig object using useMemo, otherwise the hooks will fall into an infinite loop of re-renders because the config object gets re-created each time and therefore has changed. (See: react useEffect's deps)

useNearbyPublication

Publishes a message and returns a state which describes the Nearby API status. (e.g.: connecting, published, error, ...)

export default function App() {
  const nearbyConfig = useMemo<NearbyConfig>(() => ({ apiKey: GOOGLE_API_KEY }), []);
  const nearbyStatus = useNearbyPublication(nearbyConfig, 'Hello from Nearby!');
  // ...
}

useNearbySubscription

Subscribe to nearby messages and return a state for all messages in an array, as well as a state describing the Nearby API Status. (e.g.: connecting, published, error, ...)

export default function App() {
  const nearbyConfig = useMemo<NearbyConfig>(() => ({ apiKey: GOOGLE_API_KEY }), []);
  const { nearbyMessages, nearbyStatus } = useNearbySubscription(nearbyConfig);
  return (
    <FlatList
      data={nearbyMessages}
      renderItem={({ item }) => <Text>{item}</Text>}
      />
  );
}

useNearbySearch

Search for a specific message using nearby messages. The isNearby local specifies whether the string iPhone 11 could be found using the Nearby API, and the nearbyStatus local describes the current status of the Nearby API. (e.g.: connecting, published, error, ...)

export default function App() {
  const nearbyConfig = useMemo<NearbyConfig>(() => ({ apiKey: GOOGLE_API_KEY }), []);
  const { isNearby, nearbyStatus } = useNearbySearch(nearbyConfig, 'iPhone 11');
  return (
    <Text>{isNearby ? 'iPhone 11 is nearby!' : 'iPhone 11 is far, far away.'}</Text>
  );
}

useNearbyErrorCallback

Subscribe to any errors emitted from the Nearby API.

export default function App() {
  useNearbyErrorCallback((kind, message) => {
    console.log(`Nearby API Error: ${kind}: ${message}`)
  });
}

Troubleshooting

If you're having any trouble getting the Nearby API working, please make sure you've read the Troubleshooting Page.

If that doesn't help either, create an issue.

Buy Me a Coffee at ko-fi.com

Resources

More Repositories

1

react-native-vision-camera

📸 A powerful, high-performance React Native Camera library.
Swift
6,320
star
2

react-native-mmkv

⚡️ The fastest key/value storage for React Native. ~30x faster than AsyncStorage!
C++
4,903
star
3

react-native-blurhash

🖼️ A library to show colorful blurry placeholders while your content loads.
Kotlin
1,568
star
4

react-native-multithreading

🧵 Fast and easy multithreading for React Native using JSI
C++
1,049
star
5

Colorwaver

🎨 An app to detect color palettes in the real world - powered by VisionCamera
TypeScript
548
star
6

react-native-jsi-image

🖼️ A writeable in-memory Image JSI Host Object
C++
267
star
7

react-native-tracking-transparency

🕵️ A React Native Library for interacting with the tracking API from iOS 14.
Java
208
star
8

react-native-jsi-contacts

A contacts library for React Native using JSI
C++
140
star
9

AnimatedGif

📼 A high performance .NET library for reading and creating animated GIFs
C#
127
star
10

react-native-blob-jsi-helper

A React Native library for accessing an ArrayBuffer of a Blob instance.
C++
118
star
11

react-native-jsi-library-template

Template for React Native JSI Libraries Ă  la Marc
C++
110
star
12

clean-rn

A simple CLI tool to clean all React Native caches in your project.
JavaScript
109
star
13

vision-camera-image-labeler

VisionCamera Frame Processor Plugin to label images using MLKit Vision
Java
97
star
14

ImgurSniper

📷 A quick and easy Image, Screenshot and Screen recording sharing tool
C#
85
star
15

react-native-style-utilities

Fully typed hooks and utility functions for the React Native StyleSheet API
JavaScript
78
star
16

Hotkeys

🔤 A small C# (.NET) Library which allows binding of global HotKeys to any Application's Windows (including Windows Apps such as explorer.exe), even in Background. (using P/Invokes)
C#
71
star
17

react-native-notification-badge

🔴 A notification badge count manager for React Native
Swift
47
star
18

react-native-pressable-opacity

A <PressableOpacity> and a supercharged <NativePressableOpacity> components for React Native
TypeScript
46
star
19

GenericProtocol

⚡️ A fast TCP event based buffered server/client protocol for transferring data over the (inter)net in .NET 🌐
C#
42
star
20

DiscordMusicBot

A Discord Bot for playing YouTube music.
C#
41
star
21

react-native-pressable-scale

A <PressableScale> and a supercharged <NativePressableScale> components for React Native
TypeScript
39
star
22

StorageBenchmark

Benchmark App to compare different storage libraries (MMKV, AsyncStorage, WatermelonDB, RealmDB, SQLite)
Java
29
star
23

react-native-screen-corner-radius

📱 A React Native library to get the Device's Screen's corner radius
Java
27
star
24

BrabeNetz

🧠 A fast and clean supervised neural network in C++, capable of effectively using multiple cores
C++
26
star
25

Toast

🍞 The rounded and animated Android Toast for .NET WPF/XAML
C#
26
star
26

Fiddle

📜 A lightweight code editor for editing, compiling and running code snippets/scripts supporting multiple languages and rich GUI
C
23
star
27

Jellyfish

🐟 An incredibly lightweight and type safe MVVM library for .NET WPF, Silverlight, Xamarin and UWP
C#
20
star
28

PostShot

📷 An easy to use, lightning fast and modern screenshot and screen-recording tool powered by C++ and Qt
C++
17
star
29

vision-camera-resize-plugin

A VisionCamera Frame Processor plugin for fast buffer resizing
Objective-C
17
star
30

WebUntisSharp

⏰ A Wrapper of the WebUntis JSON API for .NET
C#
14
star
31

pipestate

🏦 A minimal state management library for React.
TypeScript
13
star
32

gimp-rpc

A GIMP plugin to display Discord Rich Presence made with C
C
11
star
33

react-native-sectioned-slider

An iOS 11 Control Center inspired Slider for React Native
Ruby
10
star
34

ClipboardMonitor

A small C# Library for Monitoring Clipboard with P/Invokes (e.g.: Clipboard Content Changed event)
C#
9
star
35

GameFinder

🎮 An application for finding games to play you and your friends have on Steam
C#
8
star
36

QHotkeys

🔠 A small and lightweight cross platform C++ library implementing a system-wide hotkey system for Qt
C++
7
star
37

Keepr

A Tinder-like swipe view to keep or remove pictures from a photoshoot with extra comparison features
TypeScript
7
star
38

BmpPwd

🔐 BmpPwd is a .NET Class Library for overloadable en/decrypting strings or binary data to a System.Drawing.Image
C#
7
star
39

MaterialDesignWindowsDialogs

A new Theme (Android Material Design) for Windows Message Boxes (by hooking)
C#
7
star
40

shared-registry

Shared-Registry allows you to share objects between instances without introducing memory leaks.
TypeScript
6
star
41

dotfiles

My personal minimalistic dotfiles (.vimrc, .zshrc, .oh-my.zsh, custom scripts, ..)
Shell
6
star
42

mrousavy

✨ it's lit ✨
6
star
43

MetaLog

📝 Simple, yet effective, logging with Metadata CallerInfo for creating beautiful Log files in C#/VB .NET
C#
5
star
44

SchoolTool

📓 An App to watch your timetable and get notified of changes.
C#
3
star
45

HankHill

A discord bot for pixelating and jpegifying images
C#
3
star
46

maconvert

Easily convert .svg files to .png files
JavaScript
3
star
47

TinyRocket

A 2D Endless Unity Game; Fly up high and beat highscores with your customizable and upgradeable Rocket!
C#
3
star
48

Cirilla

🤖 Cirilla - The swiss army knife discord bot supporting many commands and systems
C#
3
star
49

Morph

🛠 A fast .NET Standard Class Library for parsing results from an SQL query to .NET objects to eliminate risky column-index hardcoding
C#
2
star
50

QPastebin

A quick Pastebin-uploader shell script using curl and the Pastebin REST API
Shell
2
star
51

QuantumSnippets

Snippets, Examples or Test code for Quantum Computers written in the Microsoft Quantum Computer Programming Language Q#
C#
1
star
52

discord-cli

CLI for discord bots
JavaScript
1
star
53

ModellbaumesseRoboter

Roboter fĂźr Modellbaumesse 2016 (TGM 3DHIT)
C++
1
star
54

Vertaler

📖 A pop-up tray application to instantly translate something from your clipboard using Google Translate
C#
1
star
55

pokecord-guesser

Guesser for Pokecord using Discord API and reverse image lookup
HTML
1
star
56

ModWnd

👺 A daemon to move any Window from within it's body (child area) while holding a modifier key (Windows/Alt)
C++
1
star
57

VisionCameraDemo

Demo for using VisionCamera + zooming
TypeScript
1
star