Giter Club home page Giter Club logo

react-native-push-notification's Introduction

React Native Push Notifications

npm version npm downloads

React Native Local and Remote Notifications for iOS and Android

State of the repository

This repository is not actively maintained. The main reason is time. The second one is probably the complexity of notifications on both iOS and Android. Since this project probably need a huge refactor to fix some issue or to implement new features. I think you should probably consider these alternatives: Notifee free since september or react-native-notifications.

If you are interested in being a maintainer of this project, feel free to ask in issues.

๐ŸŽ‰ Version 7.x is live ! ๐ŸŽ‰

Check out for changes and migration in the CHANGELOG:

Changelog

Supporting the project

Maintainers are welcome ! Feel free to contact me ๐Ÿ˜‰

Changelog

Changelog is available from version 3.1.3 here: Changelog

Installation

NPM

npm install --save react-native-push-notification

Yarn

yarn add react-native-push-notification

NOTE: If you target iOS you also need to follow the installation instructions for PushNotificationIOS since this package depends on it.

NOTE: For Android, you will still have to manually update the AndroidManifest.xml (as below) in order to use Scheduled Notifications.

Issues

Having a problem? Read the troubleshooting guide before raising an issue.

Pull Requests

Please read...

iOS manual Installation

The component uses PushNotificationIOS for the iOS part. You should follow their installation instructions.

Android manual Installation

NOTE: firebase-messaging, prior to version 15 requires to have the same version number in order to work correctly at build time and at run time. To use a specific version:

In your android/build.gradle

ext {
    googlePlayServicesVersion = "<Your play services version>" // default: "+"
    firebaseMessagingVersion = "<Your Firebase version>" // default: "21.1.0"

    // Other settings
    compileSdkVersion = <Your compile SDK version> // default: 23
    buildToolsVersion = "<Your build tools version>" // default: "23.0.1"
    targetSdkVersion = <Your target SDK version> // default: 23
    supportLibVersion = "<Your support lib version>" // default: 23.1.1
}

NOTE: localNotification() works without changes in the application part, while localNotificationSchedule() only works with these changes:

In your android/app/src/main/AndroidManifest.xml

    .....
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

    <application ....>
        <!-- Change the value to true to enable pop-up for in foreground on receiving remote notifications (for prevent duplicating while showing local notifications set this to false) -->
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_foreground"
                    android:value="false"/>
        <!-- Change the resource name to your App's accent color - or any other color you want -->
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
                    android:resource="@color/white"/> <!-- or @android:color/{name} to use a standard color -->

        <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>

        <service
            android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
     .....

If not using a built in Android color (@android:color/{name}) for the notification_color meta-data item. In android/app/src/main/res/values/colors.xml (Create the file if it doesn't exist).

<resources>
    <color name="white">#FFF</color>
</resources>

If your app has an @Override on onNewIntent in MainActivity.java ensure that function includes a super call on onNewIntent (if your MainActivity.java does not have an @Override for onNewIntent skip this):

    @Override
    public void onNewIntent(Intent intent) {
        ...
        super.onNewIntent(intent);
        ...
    }

If you use remote notifications

Make sure you have installed setup Firebase correctly.

In android/build.gradle

buildscript {
    ...
    dependencies {
        ...
        classpath('com.google.gms:google-services:4.3.3')
        ...
    }
}

In android/app/build.gradle

dependencies {
  ...
  implementation 'com.google.firebase:firebase-analytics:17.3.0'
  ...
}

apply plugin: 'com.google.gms.google-services'

Then put your google-services.json in android/app/.

Note: firebase/release-notes

The Firebase Android library firebase-core is no longer needed. This SDK included the Firebase SDK for Google Analytics.

Now, to use Analytics or any Firebase product that recommends the use of Analytics (see table below), you need to explicitly add the Analytics dependency: com.google.firebase:firebase-analytics:17.3.0.

If you don't use autolink

In android/settings.gradle

...
include ':react-native-push-notification'
project(':react-native-push-notification').projectDir = file('../node_modules/react-native-push-notification/android')

In your android/app/build.gradle

 dependencies {
    ...
    implementation project(':react-native-push-notification')
    ...
 }

Manually register module in MainApplication.java (if you did not use react-native link):

import com.dieam.reactnativepushnotification.ReactNativePushNotificationPackage;  // <--- Import Package

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
      @Override
      protected boolean getUseDeveloperSupport() {
        return BuildConfig.DEBUG;
      }

      @Override
      protected List<ReactPackage> getPackages() {

          return Arrays.<ReactPackage>asList(
              new MainReactPackage(),
              new ReactNativePushNotificationPackage() // <---- Add the Package
          );
    }
  };

  ....
}

Usage

DO NOT USE .configure() INSIDE A COMPONENT, EVEN App

If you do, notification handlers will not fire, because they are not loaded. Instead, use .configure() in the app's first file, usually index.js.

import PushNotificationIOS from "@react-native-community/push-notification-ios";
import PushNotification from "react-native-push-notification";

// Must be outside of any component LifeCycle (such as `componentDidMount`).
PushNotification.configure({
  // (optional) Called when Token is generated (iOS and Android)
  onRegister: function (token) {
    console.log("TOKEN:", token);
  },

  // (required) Called when a remote is received or opened, or local notification is opened
  onNotification: function (notification) {
    console.log("NOTIFICATION:", notification);

    // process the notification

    // (required) Called when a remote is received or opened, or local notification is opened
    notification.finish(PushNotificationIOS.FetchResult.NoData);
  },

  // (optional) Called when Registered Action is pressed and invokeApp is false, if true onNotification will be called (Android)
  onAction: function (notification) {
    console.log("ACTION:", notification.action);
    console.log("NOTIFICATION:", notification);

    // process the action
  },

  // (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
  onRegistrationError: function(err) {
    console.error(err.message, err);
  },

  // IOS ONLY (optional): default: all - Permissions to register.
  permissions: {
    alert: true,
    badge: true,
    sound: true,
  },

  // Should the initial notification be popped automatically
  // default: true
  popInitialNotification: true,

  /**
   * (optional) default: true
   * - Specified if permissions (ios) and token (android and ios) will requested or not,
   * - if not, you must call PushNotificationsHandler.requestPermissions() later
   * - if you are not using remote notification or do not have Firebase installed, use this:
   *     requestPermissions: Platform.OS === 'ios'
   */
  requestPermissions: true,
});

Example app

Example folder contains an example app to demonstrate how to use this package. The notification Handling is done in NotifService.js.

Please test your PRs with this example app before submitting them. It'll help maintaining this repo.

Handling Notifications

When any notification is opened or received the callback onNotification is called passing an object with the notification data.

Notification object example:

{
    foreground: false, // BOOLEAN: If the notification was received in foreground or not
    userInteraction: false, // BOOLEAN: If the notification was opened by the user from the notification area or not
    message: 'My Notification Message', // STRING: The notification message
    data: {}, // OBJECT: The push data or the defined userInfo in local notifications
}

Local Notifications

PushNotification.localNotification(details: Object)

EXAMPLE:

PushNotification.localNotification({
  /* Android Only Properties */
  channelId: "your-channel-id", // (required) channelId, if the channel doesn't exist, notification will not trigger.
  ticker: "My Notification Ticker", // (optional)
  showWhen: true, // (optional) default: true
  autoCancel: true, // (optional) default: true
  largeIcon: "ic_launcher", // (optional) default: "ic_launcher". Use "" for no large icon.
  largeIconUrl: "https://www.example.tld/picture.jpg", // (optional) default: undefined
  smallIcon: "ic_notification", // (optional) default: "ic_notification" with fallback for "ic_launcher". Use "" for default small icon.
  bigText: "My big text that will be shown when notification is expanded. Styling can be done using HTML tags(see android docs for details)", // (optional) default: "message" prop
  subText: "This is a subText", // (optional) default: none
  bigPictureUrl: "https://www.example.tld/picture.jpg", // (optional) default: undefined
  bigLargeIcon: "ic_launcher", // (optional) default: undefined
  bigLargeIconUrl: "https://www.example.tld/bigicon.jpg", // (optional) default: undefined
  color: "red", // (optional) default: system default
  vibrate: true, // (optional) default: true
  vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000
  tag: "some_tag", // (optional) add tag to message
  group: "group", // (optional) add group to message
  groupSummary: false, // (optional) set this notification to be the group summary for a group of notifications, default: false
  ongoing: false, // (optional) set whether this is an "ongoing" notification
  priority: "high", // (optional) set notification priority, default: high
  visibility: "private", // (optional) set notification visibility, default: private
  ignoreInForeground: false, // (optional) if true, the notification will not be visible when the app is in the foreground (useful for parity with how iOS notifications appear). should be used in combine with `com.dieam.reactnativepushnotification.notification_foreground` setting
  shortcutId: "shortcut-id", // (optional) If this notification is duplicative of a Launcher shortcut, sets the id of the shortcut, in case the Launcher wants to hide the shortcut, default undefined
  onlyAlertOnce: false, // (optional) alert will open only once with sound and notify, default: false
  
  when: null, // (optional) Add a timestamp (Unix timestamp value in milliseconds) pertaining to the notification (usually the time the event occurred). For apps targeting Build.VERSION_CODES.N and above, this time is not shown anymore by default and must be opted into by using `showWhen`, default: null.
  usesChronometer: false, // (optional) Show the `when` field as a stopwatch. Instead of presenting `when` as a timestamp, the notification will show an automatically updating display of the minutes and seconds since when. Useful when showing an elapsed time (like an ongoing phone call), default: false.
  timeoutAfter: null, // (optional) Specifies a duration in milliseconds after which this notification should be canceled, if it is not already canceled, default: null

  messageId: "google:message_id", // (optional) added as `message_id` to intent extras so opening push notification can find data stored by @react-native-firebase/messaging module. 

  actions: ["Yes", "No"], // (Android only) See the doc for notification actions to know more
  invokeApp: true, // (optional) This enable click on actions to bring back the application to foreground or stay in background, default: true

  /* iOS only properties */
  category: "", // (optional) default: empty string
  subtitle: "My Notification Subtitle", // (optional) smaller title below notification title

  /* iOS and Android properties */
  id: 0, // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID
  title: "My Notification Title", // (optional)
  message: "My Notification Message", // (required)
  picture: "https://www.example.tld/picture.jpg", // (optional) Display an picture with the notification, alias of `bigPictureUrl` for Android. default: undefined
  userInfo: {}, // (optional) default: {} (using null throws a JSON value '<null>' error)
  playSound: false, // (optional) default: true
  soundName: "default", // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
  number: 10, // (optional) Valid 32 bit integer specified as string. default: none (Cannot be zero)
  repeatType: "day", // (optional) Repeating interval. Check 'Repeating Notifications' section for more info.
});

Scheduled Notifications

PushNotification.localNotificationSchedule(details: Object)

EXAMPLE:

PushNotification.localNotificationSchedule({
  //... You can use all the options from localNotifications
  message: "My Notification Message", // (required)
  date: new Date(Date.now() + 60 * 1000), // in 60 secs
  allowWhileIdle: false, // (optional) set notification to work while on doze, default: false

  /* Android Only Properties */
  repeatTime: 1, // (optional) Increment of configured repeatType. Check 'Repeating Notifications' section for more info.
});

Get the initial notification

PushNotification.popInitialNotification(callback)

EXAMPLE:

PushNotification.popInitialNotification((notification) => {
  console.log('Initial Notification', notification);
});

Custom sounds

In android, add your custom sound file to [project_root]/android/app/src/main/res/raw

In iOS, add your custom sound file to the project Resources in xCode.

In the location notification json specify the full file name:

soundName: 'my_sound.mp3'

Channel Management (Android)

To use channels, create them at startup and pass the matching channelId through to PushNotification.localNotification or PushNotification.localNotificationSchedule.

import PushNotification, {Importance} from 'react-native-push-notification';
...
  PushNotification.createChannel(
    {
      channelId: "channel-id", // (required)
      channelName: "My channel", // (required)
      channelDescription: "A channel to categorise your notifications", // (optional) default: undefined.
      playSound: false, // (optional) default: true
      soundName: "default", // (optional) See `soundName` parameter of `localNotification` function
      importance: Importance.HIGH, // (optional) default: Importance.HIGH. Int value of the Android notification importance
      vibrate: true, // (optional) default: true. Creates the default vibration pattern if true.
    },
    (created) => console.log(`createChannel returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
  );

NOTE: Without channel, notifications don't work

In the notifications options, you must provide a channel id with channelId: "your-channel-id", if the channel doesn't exist the notification might not be triggered. Once the channel is created, the channel cannot be updated. Make sure your channelId is different if you change these options. If you have created a channel in another way, it will apply options of the channel.

If you want to use a different default channel for remote notification, refer to the documentation of Firebase:

Set up a Firebase Cloud Messaging client app on Android

  <meta-data
      android:name="com.google.firebase.messaging.default_notification_channel_id"
      android:value="@string/default_notification_channel_id" />

For local notifications, the same kind of option is available:

  • you can use:
      <meta-data
          android:name="com.dieam.reactnativepushnotification.default_notification_channel_id"
          android:value="@string/default_notification_channel_id" />
  • If not defined, fallback to the Firebase value defined in the AndroidManifest:
      <meta-data
          android:name="com.google.firebase.messaging.default_notification_channel_id"
          android:value="..." />
  • If not defined, fallback to the default Firebase channel id fcm_fallback_notification_channel

List channels

You can list available channels with:

PushNotification.getChannels(function (channel_ids) {
  console.log(channel_ids); // ['channel_id_1']
});

Channel exists

You can check if a channel exists with:

PushNotification.channelExists(channel_id, function (exists) {
  console.log(exists); // true/false
});

Channel blocked

You can check if a channel blocked with:

PushNotification.channelBlocked(channel_id, function (blocked) {
  console.log(blocked); // true/false
});

Delete channel

You can delete a channel with:

PushNotification.deleteChannel(channel_id);

Cancelling notifications

1) cancelLocalNotification

The id parameter for PushNotification.localNotification is required for this operation. The id supplied will then be used for the cancel operation.

PushNotification.localNotification({
    ...
    id: '123'
    ...
});
PushNotification.cancelLocalNotification('123');

2) cancelAllLocalNotifications

PushNotification.cancelAllLocalNotifications()

Cancels all scheduled notifications AND clears the notifications alerts that are in the notification centre.

3) removeAllDeliveredNotifications

PushNotification.removeAllDeliveredNotifications();

Remove all delivered notifications from Notification Center

4) getDeliveredNotifications

PushNotification.getDeliveredNotifications(callback);

Provides you with a list of the appโ€™s notifications that are still displayed in Notification Center

Parameters:

Name Type Required Description
callback function Yes Function which receive an array of delivered notifications.

A delivered notification is an object containing:

  • identifier : The identifier of this notification.
  • title : The title of this notification.
  • body : The body of this notification.
  • category : The category of this notification (optional).
  • userInfo : An object containing additional notification data (optional).
  • thread-id : The thread identifier of this notification, if has one.

5) removeDeliveredNotifications

PushNotification.removeDeliveredNotifications(identifiers);

Removes the specified notifications from Notification Center

Parameters:

Name Type Required Description
identifiers array Yes Array of notification identifiers.

6) getScheduledLocalNotifications

PushNotification.getScheduledLocalNotifications(callback);

Provides you with a list of the appโ€™s scheduled local notifications that are yet to be displayed

Parameters:

Name Type Required Description
callback function Yes Function which receive an array of delivered notifications.

Returns an array of local scheduled notification objects containing:

Name Type Description
id number The identifier of this notification.
date Date The fire date of this notification.
title string The title of this notification.
message string The message body of this notification.
soundName string The sound name of this notification.
repeatInterval number (Android only) The repeat interval of this notification.
number number App notification badge count number.
data any The user info of this notification.

Abandon Permissions

PushNotification.abandonPermissions()

Revokes the current token and unregister for all remote notifications received via APNS or FCM.

Notification priority

(optional) Specify priority to set priority of notification. Default value: "high"

Available options:

"max" = NotficationCompat.PRIORITY_MAX\
"high" = NotficationCompat.PRIORITY_HIGH\
"low" = NotficationCompat.PRIORITY_LOW\
"min" = NotficationCompat.PRIORITY_MIN\
"default" = NotficationCompat.PRIORITY_DEFAULT

More information: https://developer.android.com/reference/android/app/Notification.html#PRIORITY_DEFAULT

Notification visibility

(optional) Specify visibility to set visibility of notification. Default value: "private"

Available options:

"private" = NotficationCompat.VISIBILITY_PRIVATE\
"public" = NotficationCompat.VISIBILITY_PUBLIC\
"secret" = NotficationCompat.VISIBILITY_SECRET 

More information: https://developer.android.com/reference/android/app/Notification.html#VISIBILITY_PRIVATE

Notification importance

(optional) Specify importance to set importance of notification. Default value: Importance.HIGH
Constants available on the Importance object. import PushNotification, {Importance} from 'react-native-push-notification';

Available options:

Importance.DEFAULT = NotificationManager.IMPORTANCE_DEFAULT\
Importance.HIGH = NotificationManager.IMPORTANCE_HIGH\
Importance.LOW = NotificationManager.IMPORTANCE_LOW\
Importance.MIN = NotificationManager.IMPORTANCE_MIN\
Importance.NONE= NotificationManager.IMPORTANCE_NONE\
Importance.UNSPECIFIED = NotificationManager.IMPORTANCE_UNSPECIFIED

More information: https://developer.android.com/reference/android/app/NotificationManager#IMPORTANCE_DEFAULT

Show notifications while the app is in foreground

If you want a consistent results in Android & iOS with the most flexibility, it is best to handle it manually by prompting a local notification when onNotification is triggered by a remote push notification on foreground (check notification.foreground prop).

Watch out for an infinite loop triggering onNotification - remote & local notification will trigger it. You can overcome this by marking local notifications' data.

Notification while idle

(optional) Specify allowWhileIdle to set if the notification should be allowed to execute even when the system is on low-power idle modes.

On Android 6.0 (API level 23) and forward, the Doze was introduced to reduce battery consumption when the device is unused for long periods of time. But while on Doze the AlarmManager alarms (used to show scheduled notifications) are deferred to the next maintenance window. This may cause the notification to be delayed while on Doze.

This can significantly impact the power use of the device when idle. So it must only be used when the notification is required to go off on a exact time, for example on a calendar notification.

More information: https://developer.android.com/training/monitoring-device-state/doze-standby

Repeating Notifications

(optional) Specify repeatType and optionally repeatTime (Android-only) while scheduling the local notification. Check the local notification example above.

iOS

Property repeatType can only be month, week, day, hour, minute.

NOTE: repeatTime do not work with iOS.

Android

Property repeatType could be one of month, week, day, hour, minute, time.

The interval used can be configured to a different interval using repeatTime. If repeatType is time, repeatTime must be specified as the number of milliseconds between each interval. For example, to configure a notification every other day

PushNotification.localNotificationSchedule({
    ...
    repeatType: 'day',
    repeatTime: 2,
    ...
});

Notification Actions

(Android Only)

This is done by specifying an actions parameters while configuring the local notification. This is an array of strings where each string is a notification action that will be presented with the notification.

For e.g. actions: ['Accept', 'Reject']

When you handle actions in background (invokeApp: false), you can open the application and pass the initial notification by using use PushNotification.invokeApp(notification).

Make sure you have the receiver in AndroidManifest.xml:

  <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />

Notifications with inline reply:

You must register an action as "ReplyInput", this will show in the notifications an input to write in.

EXAMPLE:

PushNotification.localNotificationSchedule({
  message: "My Notification Message", // (required)
  date: new Date(Date.now() + (60 * 1000)), // in 60 secs
  actions: ["ReplyInput"],
  reply_placeholder_text: "Write your response...", // (required)
  reply_button_text: "Reply" // (required)
});

To get the text from the notification:

...
if(notification.action === "ReplyInput"){
  console.log("texto", notification.reply_text)// this will contain the inline reply text. 
}
...

For iOS, you can use:

PushNotification.setNotificationCategories(categories);

And use the category field in the notification.

Documentation here to add notification actions.

Set application badge icon

PushNotification.setApplicationIconBadgeNumber(number: number)

Works natively in iOS.

Uses the ShortcutBadger on Android, and as such will not work on all Android devices.

Android Only Methods

PushNotification.subscribeToTopic(topic: string)

Subscribe to a topic (works only with Firebase)

PushNotification.unsubscribeFromTopic(topic: string)

Unsubscribe from a topic (works only with Firebase)

Android Custom Notification Handling

Unlike iOS, Android apps handle the creation of their own notifications. React Native Push Notifications does a "best guess" to create and handle incoming notifications. However, when using 3rd party notification platforms and tools, the initial notification creation process may need to be customized.

Customizing Notification Creation

If your notification service uses a custom data payload format, React Native Push Notifications will not be able to parse the data correctly to create an initial notification.

For these cases, you should:

  1. Remove the intent handler configuration for React Native Push Notifications from your android/app/src/main/AndroidManifest.xml.
  2. Implement initial notification creation as per the instructions from your Provider.

Handling Custom Payloads

Data payloads of notifications from 3rd party services may not match the format expected by React Native Push Notification. When tapped, these notifications will not pass the details and data to the onNotification() event handler. Custom IntentHandlers allow you to fix this so that correct notification objects are sent to your onNotification() method.

Custom handlers are added in Application init or MainActivity.onCreate() methods:

RNPushNotification.IntentHandlers.add(new RNPushNotification.RNIntentHandler() {
  @Override
  public void onNewIntent(Intent intent) {
    // If your provider requires some parsing on the intent before the data can be
    // used, add that code here. Otherwise leave empty.
  }

  @Nullable
  @Override
  public Bundle getBundleFromIntent(Intent intent) {
    // This should return the bundle data that will be serialized to the `notification.data`
    // property sent to the `onNotification()` handler. Return `null` if there is no data
    // or this is not an intent from your provider.
    
    // Example:
    if (intent.hasExtra("MY_NOTIFICATION_PROVIDER_DATA_KEY")) {
      return intent.getBundleExtra("MY_NOTIFICATION_PROVIDER_DATA_KEY");
    }
    return null;
  }
});

Checking Notification Permissions

PushNotification.checkPermissions(callback: Function) //Check permissions

callback will be invoked with a permissions object:

  • alert: boolean
  • badge: boolean
  • sound: boolean

iOS Only Methods

PushNotification.getApplicationIconBadgeNumber(callback: Function) //Get badge number

react-native-push-notification's People

Contributors

andrewtremblay avatar aranda-adapptor avatar banshianton avatar cancan101 avatar chrisspankroy avatar dallas62 avatar gabeconsalter avatar gp2mv3 avatar hojason117 avatar hosoi-appland avatar ianlin avatar joaoahmad avatar johgusta avatar kfiroo avatar leenasn avatar lorenc-tomasz avatar lukebars avatar maxkomarychev avatar mikelambert avatar mmmoussa avatar mookiies avatar nbolender avatar npomfret avatar paddy57 avatar rafaelcamaram avatar robwalkerco avatar sginn avatar superandrew213 avatar varungupta85 avatar zo0r avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-push-notification's Issues

Build failed on android

When I try to build the project for android by using react-native run-android it fails and gives the error on line compile project(':react-native-push-notification') in build.gradle

Building and installing the app on the device (cd android && ./gradlew installDebug...

FAILURE: Build failed with an exception.

  • Where:
    Build file '/Users/tayyab/react-native/PushNotifications/android/build.gradle' line: 13
  • What went wrong:
    A problem occurred evaluating root project 'PushNotifications'.
    Could not find method compile() for arguments [project ':react-native-push-notification'] on org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated@1640c151.
  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Can you please me fixing this issue?

java.lang.NullPointerException

I'm getting a null pointer exception (and application crash) when receiving a push notification.

Changing line 35 of RNPushNotificationListenerService.java to:

} catch (Exception e) {

prevents the crash and allows the push notification to appear.

Stacktrace:

04-23 22:14:22.228   983  2194 D PMS     : acquireWL(b445424): PARTIAL_WAKE_LOCK  wake:*****/com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService 0x1 18597 10242 null
04-23 22:14:22.256 18597 18675 E AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
04-23 22:14:22.256 18597 18675 E AndroidRuntime: Process: *****, PID: 18597
04-23 22:14:22.256 18597 18675 E AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
04-23 22:14:22.256 18597 18675 E AndroidRuntime:    at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
04-23 22:14:22.256 18597 18675 E AndroidRuntime:    at org.json.JSONTokener.nextValue(JSONTokener.java:94)
04-23 22:14:22.256 18597 18675 E AndroidRuntime:    at org.json.JSONObject.<init>(JSONObject.java:156)
04-23 22:14:22.256 18597 18675 E AndroidRuntime:    at org.json.JSONObject.<init>(JSONObject.java:173)
04-23 22:14:22.256 18597 18675 E AndroidRuntime:    at com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService.getPushData(RNPushNotificationListenerService.java:34)
04-23 22:14:22.256 18597 18675 E AndroidRuntime:    at com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService.onMessageReceived(RNPushNotificationListenerService.java:19)
04-23 22:14:22.256 18597 18675 E AndroidRuntime:    at com.google.android.gms.gcm.GcmListenerService.zzq(Unknown Source)
04-23 22:14:22.256 18597 18675 E AndroidRuntime:    at com.google.android.gms.gcm.GcmListenerService.zzp(Unknown Source)
04-23 22:14:22.256 18597 18675 E AndroidRuntime:    at com.google.android.gms.gcm.GcmListenerService.zzo(Unknown Source)
04-23 22:14:22.256 18597 18675 E AndroidRuntime:    at com.google.android.gms.gcm.GcmListenerService.zza(Unknown Source)
04-23 22:14:22.256 18597 18675 E AndroidRuntime:    at com.google.android.gms.gcm.GcmListenerService$1.run(Unknown Source)
04-23 22:14:22.256 18597 18675 E AndroidRuntime:    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
04-23 22:14:22.256 18597 18675 E AndroidRuntime:    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
04-23 22:14:22.256 18597 18675 E AndroidRuntime:    at java.lang.Thread.run(Thread.java:818)
04-23 22:15:01.187 18597 18675 D Process : killProcess, pid=18597
04-23 22:15:01.198 18597 18675 D Process : com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException:113 java.lang.ThreadGroup.uncaughtException:693 java.lang.ThreadGroup.uncaughtException:690 

Android: 'onNotification' not executing when app is closed and clicked to notification

[android]
Hello, when I put app in the background and I get push notification then onNotification is executed as I expect. But when I close app (using android back button) and I get push notification then onNotification is not executed.

I know onNotification is fired from Java in onNewIntent method. But I really need to pass some data from notification into JavaScript when application was closed before and I click on notification.

How to do it?

Windows: 240 Character limit

Getting this error when I try to compile in Windows:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-push-notification:mergeReleaseResources'.
> C:\Development\ec_app\node_modules\react-native-push-notification\RNPushNotificationAndroid\build\intermediates\exploded-aar\com.google.android.gms\play-services-base\8.3.0\res\drawable-xxhdpi\common_google_signin_btn_icon_light_focused.9.png: Error: File path too long on Windows, keep below 240 characters : C:\Development\ec_app\node_modules\react-native-push-notification\RNPushNotificationAndroid\build\intermediates\exploded-aar\com.google.android.gms\play-services-base\8.3.0\res\drawable-xxhdpi\common_google_signin_btn_icon_light_focused.9.png

I'm able to solve this by shortening my Development folder to Dev, but some people might not be so lucky. I'm not sure if it's easy for you to shorten some of your filenames to avoid this issue for other people?

iOS - Notifications not showing up when app is in background

I can trigger notifications when the app is in the foreground (i.e. they appear in the dropdown notifications area) but they don't seem to appear once the app is in the background.

// AppDelegate.m
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#import "AppDelegate.h"

#import "RCTRootView.h"

#import "RCTPushNotificationManager.h"


@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;

  /**
   * Loading JavaScript code - uncomment the one you want.
   *
   * OPTION 1
   * Load from development server. Start the server from the repository root:
   *
   * $ npm start
   *
   * To run on device, change `localhost` to the IP address of your computer
   * (you can get this by typing `ifconfig` into the terminal and selecting the
   * `inet` value under `en0:`) and make sure your computer and iOS device are
   * on the same Wi-Fi network.
   */

  jsCodeLocation = [NSURL URLWithString:@"http://192.168.1.101:8081/index.ios.bundle?platform=ios&dev=true"];

  /**
   * OPTION 2
   * Load from pre-bundled file on disk. The static bundle is automatically
   * generated by the "Bundle React Native code and images" build step when
   * running the project on an actual device or running the project on the
   * simulator in the "Release" build configuration.
   */

//   jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"olisReactNative"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

// Required to register for notifications
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
[RCTPushNotificationManager didRegisterUserNotificationSettings:notificationSettings];
}
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[RCTPushNotificationManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification event.
// https://facebook.github.io/react-native/docs/pushnotificationios.html#content
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification
{
NSLog(@"didReceiveRemoteNotification");
[RCTPushNotificationManager didReceiveRemoteNotification:notification];
}

// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
[RCTPushNotificationManager didReceiveLocalNotification:notification];
}

@end

    PushNotification.localNotification({
      // No idea why, but seems like I need the Android only properties as well to trigger a notification in the dropdown

      /* Android Only Properties */
      id: 0, // (optional) default: Autogenerated Unique ID
      title: "My Notification Title", // (optional)
      ticker: "My Notification Ticker", // (optional)
      largeIcon: "ic_launcher", // (optional) default: "ic_launcher"
      smallIcon: "ic_notification", // (optional) default: "ic_notification" with fallback for "ic_launcher"

      /* iOS and Android properties */
      message: "My Notification Message" // (required)
    });

IOS notification press event

I am sorry as this is less an issue as a cry for help :)
in android I have the 'sysNotificationClick' I can listen to, is there an equivalent one for IOS?
I need to open my app on specific pages according to the notifications I receive. and I am a bit dumbfounded as to how to do it...

thanks.

How do you get the device token in android?

Hi,
How could I get the device token for android using this library. I configured the PushNotification object as documented. I can send local notifications, but callback for register event is never called. Do I need to call some method? Thanks

[Android] Cancel remote notifications

Is it possible to somehow clear or dismiss remote notifications for android? PushNotification.cancelAllLocalNotifications() seems to only cancels the local notifications, not the ones from server.

IOS GCM Support

Does this module support the use of GCM with IOS?
If not, is there any intended support for this in the future?

[Android] Build failed React Native 0.18.0-rc

I have some build error

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> A problem occurred configuring project ':react-native-push-notification'.
   > Could not resolve all dependencies for configuration ':react-native-push-notification:_debugCompile'.
      > Could not find com.google.android.gms:play-services-gcm:8.3.0.
        Searched in the following locations:
            file:/Users/ahmed/.m2/repository/com/google/android/gms/play-services-gcm/8.3.0/play-services-gcm-8.3.0.pom
            file:/Users/ahmed/.m2/repository/com/google/android/gms/play-services-gcm/8.3.0/play-services-gcm-8.3.0.jar
            https://jcenter.bintray.com/com/google/android/gms/play-services-gcm/8.3.0/play-services-gcm-8.3.0.pom
            https://jcenter.bintray.com/com/google/android/gms/play-services-gcm/8.3.0/play-services-gcm-8.3.0.jar
            file:/usr/local/Cellar/android-sdk/24.3.4/extras/android/m2repository/com/google/android/gms/play-services-gcm/8.3.0/play-services-gcm-8.3.0.pom
            file:/usr/local/Cellar/android-sdk/24.3.4/extras/android/m2repository/com/google/android/gms/play-services-gcm/8.3.0/play-services-gcm-8.3.0.jar
        Required by:
            myApp:react-native-push-notification:unspecified

I tried to add compile 'com.google.android.gms:play-services-gcm:8.3.0' to build.gradle but same error also tried to add classpath 'com.google.gms:google-services:1.5.0-beta2' to android/build.gradle

any solutions ?

Cannot run on android: Attempt to invoke interface method

I follow all instruction in documentation but getting weird error
https://img42.com/Bf03X
Can you help me with sorting this:
Main activity file is:

package com.nativestarter;

import com.facebook.react.ReactActivity;
import com.oblador.vectoricons.VectorIconsPackage;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import android.content.Intent; // <--- Import Intent
import com.dieam.reactnativepushnotification.ReactNativePushNotificationPackage;  // <--- Import Package

import java.util.Arrays;
import java.util.List;

import me.neo.react.StatusBarPackage;

public class MainActivity extends ReactActivity {

    private ReactNativePushNotificationPackage mReactNativePushNotificationPackage; // <------ Add Package Variable
    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "NativeStarter";
    }

    /**
     * Returns whether dev mode should be enabled.
     * This enables e.g. the dev menu.
     */
    @Override
    protected boolean getUseDeveloperSupport() {
        return BuildConfig.DEBUG;
    }

   /**
   * A list of packages used by the app. If the app uses additional views
   * or modules besides the default ones, add more packages here.
   */
    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
        new MainReactPackage(),
        new VectorIconsPackage(),
        new StatusBarPackage(this),
        mReactNativePushNotificationPackage
      );
    }

    // Add onNewIntent
    @Override
    protected void onNewIntent (Intent intent) {
      super.onNewIntent(intent);

      mReactNativePushNotificationPackage.newIntent(intent);
    }
}

onNotification is not fired on iOS

I am trying to trigger a local notification which is happening. But when I click/tap on the notification message then the onNotification() callback handler is not invoked.

Notification for Killed/Closed App

When trying to push the notification for closed app, got an error like 'undefined is not an object (evluating 'RCTToastAndroid.SHORT')'. Is this behaviour handled or did I missed something? please clarify. I am using RN 18.5.

logcat

W/ReactNativeJS(15109): Warning: Native component for "SMXIconImage" does not exist
W/ReactNativeJS(15109): Warning: Native component for "SMXIconImage" does not exist
E/ReactNativeJS(15109): undefined is not an object (evaluating 'RCTToastAndroid.SHORT')

Thanks.

Readme unclear around remote notifications

The readme has this snippet

Sending Notification Data From Server

Same parameters as PushNotification.localNotification()

It's not clear what this is actually on about - it implies you can install react-native-push-notification on your web app, and call a function to send push notificiations to your native app, which (I'm fairly certain from reading the code) it cannot do.

Support for System Icons

Add some way of doing using system drawables rather than requiring a resource in the mipmap folder:

setSmallIcon(android.R.drawable.stat_notify_sync_noanim)

onNewIntent compilation error

My MainActivity extends ReactActivity (like the react-native starter project), so after I did all the changes and run "react-native run-android" I'm getting this error:

cannot find symbol
protected void onNewIntent (Intent intent) {
^
symbol: class Intent
location: class MainActivity
1 error
:app:compileDebugJavaWithJavac FAILED

FAILURE: Build failed with an exception.

How to fix it?

Cannot read property 'initialNotifcation' of undefined

I'm getting Cannot read property 'initialNotifcation' of undefined when I try to do PushNotification.configure. I'm running this from a real device, not an emulator.

More error details

NotificationsComponent.popInitialNotification index.android.js:20

Here's my code

// MainActivity.java
package com.olisreactnative;

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

import android.content.Intent; // <--- Import Intent 
import com.dieam.reactnativepushnotification.ReactNativePushNotificationPackage;  // <--- Import Package 

import java.util.Arrays;
import java.util.List;

public class MainActivity extends ReactActivity {

    private ReactNativePushNotificationPackage mReactNativePushNotificationPackage; // <------ Add Package Variable 

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "olisReactNative";
    }

    /**
     * Returns whether dev mode should be enabled.
     * This enables e.g. the dev menu.
     */
    @Override
    protected boolean getUseDeveloperSupport() {
        return BuildConfig.DEBUG;
    }

    /**
     * A list of packages used by the app. If the app uses additional views
     * or modules besides the default ones, add more packages here.
     */
    @Override
    protected List<ReactPackage> getPackages() {
        mReactNativePushNotificationPackage = new ReactNativePushNotificationPackage(this); // <------ Initialize the Package 

        return Arrays.<ReactPackage>asList(
            new MainReactPackage(),
            mReactNativePushNotificationPackage // <---- Add the Package 
        );
    }

    // Add onNewIntent 
    @Override
    protected void onNewIntent (Intent intent) {
      super.onNewIntent(intent);

      mReactNativePushNotificationPackage.newIntent(intent);
    }
}

// config.js 
import PushNotification from 'react-native-push-notification';

export default function ({Meteor}) {
  PushNotification.configure({
    // (optional) Called when Token is generated (iOS and Android)
    onRegister(token) {
      Meteor.call('notifications.set.GCMToken', {token}, err => {
        if (err) { alert(err); }
        else {
          console.log(`Token ${token} set on server.`);
        }
      });
    },

    // (required) Called when a remote or local notification is opened or received
    onNotification(notification) {
      console.log( 'NOTIFICATION:', notification );
    },

    // ANDROID ONLY: (optional) GCM Sender ID. Same as the project number
    senderID: 'mysenderId',

    // IOS ONLY (optional): default: all - Permissions to register.
    permissions: {
      alert: true,
      badge: true,
      sound: true,
    },

    // Should the initial notification be popped automatically
    // default: true
    popInitialNotification: true,

    /**
      * IOS ONLY: (optional) default: true
      * - Specified if permissions will requested or not,
      * - if not, you must call PushNotificationsHandler.requestPermissions() later
      */
    requestPermissions: true,
  });
}

requestPermissions callback ?

Hey there!

It appears that requestPermissions doesn't have a callback, which means I'm not able to know wether or not the prompt has been taped! Any idea on how I could do?

Cheers!

Opaque Android Error

I have installed the NPM package, and followed the instructions in the readme. As soon as a boot the app, I get the error below (found in logcat, it never actually hits my code).

I've googled for a bit, but found no real solutions. If I remove the package from the compile the app builds and runs fine:

java.lang.NoSuchMethodError: No static method zzy(Ljava/lang/Object;)Ljava/lang/Object; in class Lcom/google/android/gms/common/internal/zzx; or its super classes (declaration of 'com.google.android.gms.common.internal.zzx' appears in /data/app/com.softwriters.pod-1/base.apk)
03-07 13:45:41.927 3595 3595 E AndroidRuntime: at com.google.android.gms.measurement.internal.zzt.zzaU(Unknown Source)
03-07 13:45:41.927 3595 3595 E AndroidRuntime: at com.google.android.gms.measurement.AppMeasurementContentProvider.onCreate(Unknown Source)
03-07 13:45:41.927 3595 3595 E AndroidRuntime: at android.content.ContentProvider.attachInfo(ContentProvider.java:1748)
03-07 13:45:41.927 3595 3595 E AndroidRuntime: at android.content.ContentProvider.attachInfo(ContentProvider.java:1723)
03-07 13:45:41.927 3595 3595 E AndroidRuntime: at android.app.ActivityThread.installProvider(ActivityThread.java:5153)
03-07 13:45:41.927 3595 3595 E AndroidRuntime: at android.app.ActivityThread.installContentProviders(ActivityThread.java:4748)
03-07 13:45:41.927 3595 3595 E AndroidRuntime: at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4688)
03-07 13:45:41.927 3595 3595 E AndroidRuntime: at android.app.ActivityThread.-wrap1(ActivityThread.java)
03-07 13:45:41.927 3595 3595 E AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405)
03-07 13:45:41.927 3595 3595 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
03-07 13:45:41.927 3595 3595 E AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
03-07 13:45:41.927 3595 3595 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
03-07 13:45:41.927 3595 3595 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
03-07 13:45:41.927 3595 3595 E AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-07 13:45:41.927 3595 3595 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-07 13:45:41.932 1287 1730 W ActivityManager: Force finishing activity app/.MainActivity

Working with gb-native-router

Hi there!
I would like to combine the push functionality in order to load an article sent from server.
For that matter, i'm using gb-native-router library.
Do you have any idea about combining them?

Build fails with v1.0.4

I updated to v1.0.4 and my gradle build fails. Reverting to v1.0.3 fixes the build errors.

Error:

Cannot evaluate module react-native-push-notification : Configuration with name 'default' not found.

Stacktrace:

./gradlew installDebug --stacktrace

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> Cannot evaluate module react-native-push-notification : Configuration with name 'default' not found.

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':app'.
    at org.gradle.configuration.project.LifecycleProjectEvaluator.addConfigurationFailure(LifecycleProjectEvaluator.java:79)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:74)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:61)
    at org.gradle.api.internal.project.AbstractProject.evaluate(AbstractProject.java:487)
    at org.gradle.api.internal.project.AbstractProject.evaluate(AbstractProject.java:85)
    at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:47)
    at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:35)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:129)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:90)
    at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28)
    at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:50)
    at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:27)
    at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:40)
    at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:169)
    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:237)
    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:210)
    at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
    at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:206)
    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
    at org.gradle.launcher.Main.doAction(Main.java:33)
    at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
    at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:54)
    at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:35)
    at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
    at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:30)
    at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:127)
    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
Caused by: org.gradle.api.UnknownProjectException: Cannot evaluate module react-native-push-notification : Configuration with name 'default' not found.
    at com.android.build.gradle.internal.DependencyManager.ensureConfigured(DependencyManager.java:666)
    at com.android.build.gradle.internal.DependencyManager.resolveDependencyForConfig(DependencyManager.java:235)
    at com.android.build.gradle.internal.DependencyManager.resolveDependencies(DependencyManager.java:135)
    at com.android.build.gradle.internal.TaskManager.resolveDependencies(TaskManager.java:317)
    at com.android.build.gradle.internal.VariantManager$8.call(VariantManager.java:573)
    at com.android.build.gradle.internal.VariantManager$8.call(VariantManager.java:570)
    at com.android.builder.profile.ThreadRecorder$1.record(ThreadRecorder.java:48)
    at com.android.builder.profile.Recorder$record.call(Unknown Source)
    at com.android.build.gradle.internal.profile.SpanRecorders.record(SpanRecorders.groovy:69)
    at com.android.build.gradle.internal.VariantManager.createVariantData(VariantManager.java:569)
    at com.android.build.gradle.internal.VariantManager.createVariantDataForProductFlavors(VariantManager.java:722)
    at com.android.build.gradle.internal.VariantManager.populateVariantDataList(VariantManager.java:442)
    at com.android.build.gradle.internal.VariantManager.createAndroidTasks(VariantManager.java:258)
    at com.android.build.gradle.BasePlugin$_createAndroidTasks_closure15.doCall(BasePlugin.groovy:483)
    at com.android.build.gradle.BasePlugin$_createAndroidTasks_closure15.doCall(BasePlugin.groovy)
    at com.android.build.gradle.internal.profile.SpanRecorders$2.call(SpanRecorders.groovy:52)
    at com.android.builder.profile.ThreadRecorder$1.record(ThreadRecorder.java:48)
    at com.android.build.gradle.internal.profile.SpanRecorders.record(SpanRecorders.groovy:54)
    at com.android.build.gradle.BasePlugin.createAndroidTasks(BasePlugin.groovy:482)
    at com.android.build.gradle.BasePlugin$_createTasks_closure13_closure17.doCall(BasePlugin.groovy:415)
    at com.android.build.gradle.BasePlugin$_createTasks_closure13_closure17.doCall(BasePlugin.groovy)
    at com.android.build.gradle.internal.profile.SpanRecorders$2.call(SpanRecorders.groovy:52)
    at com.android.builder.profile.ThreadRecorder$1.record(ThreadRecorder.java:48)
    at com.android.build.gradle.internal.profile.SpanRecorders.record(SpanRecorders.groovy:54)
    at com.android.build.gradle.BasePlugin$_createTasks_closure13.doCall(BasePlugin.groovy:414)
    at org.gradle.listener.ClosureBackedMethodInvocationDispatch.dispatch(ClosureBackedMethodInvocationDispatch.java:40)
    at org.gradle.listener.ClosureBackedMethodInvocationDispatch.dispatch(ClosureBackedMethodInvocationDispatch.java:25)
    at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:87)
    at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:31)
    at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy11.afterEvaluate(Unknown Source)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:67)
    ... 33 more
Caused by: org.gradle.api.artifacts.UnknownConfigurationException: Configuration with name 'default' not found.
    at org.gradle.api.internal.artifacts.configurations.DefaultConfigurationContainer.createNotFoundException(DefaultConfigurationContainer.java:81)
    at org.gradle.api.internal.DefaultNamedDomainObjectCollection.getByName(DefaultNamedDomainObjectCollection.java:210)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfigurationContainer.getByName(DefaultConfigurationContainer.java:71)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfigurationContainer.getByName(DefaultConfigurationContainer.java:34)
    at org.gradle.api.internal.artifacts.dependencies.DefaultProjectDependency.getProjectConfiguration(DefaultProjectDependency.java:69)
    at org.gradle.api.internal.artifacts.dependencies.DefaultProjectDependency_Decorated.getProjectConfiguration(Unknown Source)
    at com.android.build.gradle.internal.DependencyManager.ensureConfigured(DependencyManager.java:664)
    ... 64 more


BUILD FAILED

Total time: 16.569 secs

Clarification on Android notifications

Does this package allow Android notifications to work in a similar manner to iOS? We're having trouble figuring out the correct implementation.

In our component:

componentDidMount() {
  PushNotification.configure({
    onRegister: this.onPushNotificationRegister,
    onNotification: this.onPushNotification,
    senderID: 'foo'
  });
}

App in foreground
Both iOS and Android call this.onPushNotification.

App in background

  • iOS natively displays a notification and when you tap it the app takes focus and this.onPushNotification is then called.
  • Android gets the notification in the background and instantly calls this.onPushNotification but we want this to work like iOS. If we add notification to the GCM payload (see payload docs) then Android natively displays a notification for us (great) but when clicking on it, nothing happens in the app (not great). Instead, should we not include a notification and call PushNotification.localNotification() which some data passed in?

App not open

  • iOS natively displays a notification and when you tap it the app takes focus and this.onPushNotification is then called.
  • I think Android does nothing unless you include the notification payload from gcm? We tried adding a click_action that opens the app when you tap the notification but then this.onPushNotification is never called.

If we can figure this out, let's update the package docs.

How to access "this" inside the onNotification?

At first I had PushNotification.configure({ in index.android.js outside the class declaration but now I have it inside the componentDidMount, is anything wrong with this?

Now I want to have access to this.state inside the onNotification but I don't know how.

I tryed to add a PushNotification.addEventListener to an external method but the class doesn't accept it.

Babel 6.4.x typeof error

We get this error calling PushNotification.configure

undefined is not a function (evaluating 'babelHelpers.typeof(params)')

Getting this on line 32 of index.js

I am guessing this is probably more of a Babel issue. However, we created a fork that removes the check for an 'object' which got us working around the issue for now.

register to google

how to register to google to obtain the android id? I could not find any function to call registration.

onRegister not called (Android)

I took the sample code
onRegister: function(token) { console.log( 'TOKEN:', token ); },
But onRegister is not called on Android
How do I get the device token?

Support for Expandable text

Currently there is no support for BigTextStyle for expandable text. Is it good to add it as an extra parameter in the bundle with "bigText" for the same?

Solved: Hard crash on Android, GMS & Play Services related

Update: If you're seeing crashes with this library and logs point to com.google.android.gcm, it's possible that another project dependency is requiring a newer version of Play Services than this one. In our case, we're using react-native-maps, which lists com.google.android.gms:play-services-maps:8.4.0 as a dependency. This library lists com.google.android.gms:play-services-gcm:8.3.0. Forking this library and updating that dependency to number 8.4.0 resolved our crash.

Implementing this library in our app results in hard crashes when building the Android app. We've double and triple checked the installation instructions and everything is as instructed. When running react-native run-android, the app immediately crashes with the standard Unfortunately [App] has stopped..

The only (seemingly) relevant crash logs from logcat are below. Any insight into why this might be happening? No mention of this in any other issues so far.

W/dalvikvm(12272): threadid=1: thread exiting with uncaught exception (group=0x415f4ba8)
E/AndroidRuntime(12272): FATAL EXCEPTION: main
E/AndroidRuntime(12272): Process: com.[redacted], PID: 12272
E/AndroidRuntime(12272): java.lang.NoSuchMethodError: com.google.android.gms.common.internal.zzx.zzy
E/AndroidRuntime(12272):        at com.google.android.gms.measurement.internal.zzt.zzaU(Unknown Source)
E/AndroidRuntime(12272):        at com.google.android.gms.measurement.AppMeasurementContentProvider.onCreate(Unknown Source)
E/AndroidRuntime(12272):        at android.content.ContentProvider.attachInfo(ContentProvider.java:1591)
E/AndroidRuntime(12272):        at android.content.ContentProvider.attachInfo(ContentProvider.java:1562)
E/AndroidRuntime(12272):        at android.app.ActivityThread.installProvider(ActivityThread.java:4790)
E/AndroidRuntime(12272):        at android.app.ActivityThread.installContentProviders(ActivityThread.java:4385)
E/AndroidRuntime(12272):        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4325)
E/AndroidRuntime(12272):        at android.app.ActivityThread.access$1500(ActivityThread.java:135)
E/AndroidRuntime(12272):        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
E/AndroidRuntime(12272):        at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(12272):        at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime(12272):        at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime(12272):        at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(12272):        at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(12272):        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/AndroidRuntime(12272):        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime(12272):        at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager(  760):   Force finishing activity com.[redacted]/.MainActivity

Crash: JSON value of type NSDate cannot be converted to a date

Hello!

I'm scheduling multiple notifications, but sometimes (that's the worst part; it's just sometimes) it crashes and throws this error:

JSON value '2016-05-25 04:00:00 +0000' of type NSDate cannot be converted to a date

Here is the code used to schedule:

static scheduleNotification(quoteDate, quoteHours, quoteOfDay){
    let notifDate = new Date(quoteDate);
    notifDate.setHours(quoteHours.hour, quoteHours.mins, 0);
    let message = '"'+quoteOfDay.frase + '" - ' + quoteOfDay.autor;
    PushNotification.localNotificationSchedule({
        id: 0,
        message: message,
        date: notifDate
    })
}

I've tried to use "date: new Date(notifDate)", but no lucky.
Any ideas?

Thank you

Edit:

It seems to be related with this issue: facebook/react-native#4049

Could not find com.google.android.gms:play-services-gcm:8.4.0

I'm getting the following trying to run on Android:

`FAILURE: Build failed with an exception.

  • What went wrong:
    A problem occurred configuring project ':app'.

    A problem occurred configuring project ':react-native-push-notification'.
    Could not resolve all dependencies for configuration ':react-native-push-notification:_debugCompile'.
    Could not find com.google.android.gms:play-services-gcm:8.4.0.
    Searched in the following locations:
    ...
    Required by:
    My101:react-native-push-notification:unspecified`

What am I missing?

Can we lower the dependency to play-services-gcm?

Anyone knows if the play-services-gcm dependency has to be at 8.4.0? I see it was bumped here, but not sure about the context.

I just ask because we've seen devices that have gcm at 7.x, and updating is surprisingly painful to the user (basically on this one device I simply don't see "Google Play Services" in the list of apps that needs to be updated, and can't seem to find it searching the Play store either).

The good news is that I was able to get the basic flow of asking for permissions and getting a token to work with this package with dependency set to 7.8.0, so I'm wondering if we can't just lower it here.

'onNotification' not fired in background - (iOS)

I'm using OneSignal to send push notifications to my react-native app. On iOS, everything works really well when the app is in the foreground. When the app is in the background, I see the notification on the lockscreen but my onNotification is not fired until I open the app (tried it both with the screen on and the screen off)

Haven't tested this yet on Android

Issue with `id` -> Key id expected String but value was a java.lang.Double.

The following:

    PushNotification.localNotification({
        id: 0, // (optional) default: Autogenerated Unique ID
        message: "My Notification Message" // (required)
    });

yields:

03-22 17:36:39.305 21670-23422/com.afitness2 W/Bundle: Key id expected String but value was a java.lang.Double.  The default value <null> was returned.
03-22 17:36:39.305 21670-23422/com.afitness2 W/Bundle: Attempt to cast generated internal exception:
                                                       java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String
                                                           at android.os.BaseBundle.getString(BaseBundle.java:923)
                                                           at com.dieam.reactnativepushnotification.modules.RNPushNotificationHelper.sendNotification(RNPushNotificationHelper.java:99)
                                                           at com.dieam.reactnativepushnotification.modules.RNPushNotification.presentLocalNotification(RNPushNotification.java:145)
                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                           at com.facebook.react.bridge.BaseJavaModule$JavaMethod.invoke(BaseJavaModule.java:249)
                                                           at com.facebook.react.bridge.NativeModuleRegistry$ModuleDefinition.call(NativeModuleRegistry.java:158)
                                                           at com.facebook.react.bridge.NativeModuleRegistry.call(NativeModuleRegistry.java:58)
                                                           at com.facebook.react.bridge.CatalystInstanceImpl$NativeModulesReactCallback.call(CatalystInstanceImpl.java:428)
                                                           at com.facebook.react.bridge.queue.NativeRunnableDeprecated.run(Native Method)
                                                           at android.os.Handler.handleCallback(Handler.java:739)
                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                           at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:31)
                                                           at android.os.Looper.loop(Looper.java:148)
                                                           at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:184)
                                                           at java.lang.Thread.run(Thread.java:818)

removing id in the js works fine.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.