Git Product home page Git Product logo

react-native-alarm-notification's Introduction

React Native Alarm Notification

npm version npm downloads

***** Maintaner/Collaborator Needed as I am too busy to manage the issues and add new versions *****

Installing (React Native >= 0.60.0)

npm install react-native-alarm-notification --save

or

yarn add react-native-alarm-notification

If you are using react-native version 0.60 or higher you don't need to link react-native-alarm-notification. The package is automatically linked when building the app. All you need to do after installing package is:

For iOS pod installation:

npx pod-install

or

cd ios && pod install

For android, the package will be linked automatically on build.

_ IMPORTANT _

If your app crashes on Android, it could probably mean auto linking didn't work. You will need to make the following changes:

Show steps

android/app/src/main/java/<AppName>/MainApplication.java

  • add import com.emekalites.react.alarm.notification.ANPackage; on the imports section
  • add packages.add(new ANPackage()); in List<ReactPackage> getPackages();

android/app/build.gradle

add implementation project(':react-native-alarm-notification') in the dependencies block

android/settings.gradle

add:

include ':react-native-alarm-notification'
project(':react-native-alarm-notification').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-alarm-notification/android')

Installing (React Native <= 0.59.x)

Expand
npm install react-native-alarm-notification --save

or

yarn add react-native-alarm-notification

Use react-native link to add the library to your project:

react-native link react-native-alarm-notification

iOS manual Installation

Expand

> In your AppDelegate.h

Add at the top of the file:

#import <UserNotifications/UNUserNotificationCenter.h>

Then, add the 'UNUserNotificationCenterDelegate' to protocols:

- @interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate>
+ @interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate, UNUserNotificationCenterDelegate>

> In your AppDelegate.m

Add at the top of the file:

#import <RnAlarmNotification.h>
#import <UserNotifications/UNUserNotificationCenter.h>

Then, add the following lines:

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification withCompletionHandler: (void (^)(UNNotificationPresentationOptions options))completionHandler {
  [RnAlarmNotification didReceiveNotification:notification];
  completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}


- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    [RnAlarmNotification didReceiveNotificationResponse:response];
    completionHandler();
}

And then in your AppDelegate implementation, add the following:

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  ...
  
  // Define UNUserNotificationCenter
  UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  center.delegate = self;
  
  return YES;
}

To play sound in the background, make sure to add the following to the Info.plist file.

<key>UIBackgroundModes</key>
<array>
    <string>audio</string>
</array>

Android manual Installation

Expand

> In your AndroidManifest.xml

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

    <application ....>
        <receiver
            android:name="com.emekalites.react.alarm.notification.AlarmReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="ACTION_DISMISS" />
                <action android:name="ACTION_SNOOZE" />
            </intent-filter>
        </receiver>

        <receiver
            android:name="com.emekalites.react.alarm.notification.AlarmDismissReceiver"
            android:enabled="true"
            android:exported="true" />

        <receiver
            android:name="com.emekalites.react.alarm.notification.AlarmBootReceiver"
            android:directBootAware="true"
            android:enabled="false"
            android:exported="true">
            <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" />
                <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
     .....

Alarm Notification Data

Prop Description Default
auto_cancel Make this notification automatically dismissed when the user touches it. [boolean] true
channel (Android only) Required: - Specifies the channel the notification should be delivered on.. [string] "my_channel_id"
color (Android only) Required: Sets notification color. [color] "red"
data You can add any additional data that is important for the notification. data: { foo: "bar" }
fire_date Required: Set date for Alarm to get triggered. eg '04-03-2020 00:00:00'. Should be a date in the future . None
has_button Show snooze and dismiss buttons in notification. [boolean] false
large_icon (Android Only) Add a large icon to the notification content view. eg "ic_large_icon". PS: make sure to add the file in your mipmap folders [project_root]/android/app/src/main/res/mipmap* None
loop_sound Play sound continuously until you decide to stop it. [boolean] false
message Required: Add Notification message. "My Notification Message"
play_sound Play alarm notification sound. [boolean] true
schedule_type Required: Type of alarm schedule. "once" (to show alarm once) or "repeat" (to display alarm after set repeat_interval) "once"
repeat_interval Interval set to repeat alarm if schedule_type is "repeat". [minutely, hourly, daily, weekly] "hourly"
interval_value Set interval_value if repeat_interval is minutely and hourly. [number] 1
small_icon Required: Set the small icon resource, which will be used to represent the notification in the status bar. eg "ic_launcher". PS: make sure to add the file in your mipmap folders [project_root]/android/app/src/main/res/mipmap* "ic_launcher"
snooze_interval Interval set to show alarm after snooze button is tapped. [number] in minutes 1
sound_name Set audio file to play when alarm is triggered. example "sound_name.mp3". Add the file in your res/raw folder [project_root]/android/app/src/main/res/raw/ for android and in your ios folder [project_root]/ios/ for iOS. PS: After adding file in your iOS folder, open your application in xcode and drag your audio file into your project. None
sound_names Set multiple audio files to play when alarm is triggered, each file will be picked to play at random. Separate files with a comma (,) example "sound_name1.mp3,sound_name2.mp3". PS: make sure to add the files in your res/raw folder [project_root]/android/app/src/main/res/raw/ None
tag Add a tag id to notification. None
ticker Set the "ticker" text which is sent to accessibility services.. [String] None
title Required: Add a title to notification. "My Notification Title"
vibrate Set vibration when alarm is triggered. [boolean] true
vibration Set number of milliseconds to vibrate. [number] 100
use_big_text (Android only) Set notification message style as big text. [boolean] false
volume Set volume. [number between 0.0 and 1.0] 0.5
bypass_dnd (Android only) Sets whether or not notifications posted to this channel can interrupt the user false

Usage

import ReactNativeAN from 'react-native-alarm-notification';

const fireDate = ReactNativeAN.parseDate(new Date(Date.now() + 1000));     // set the fire date for 1 second from now
or
const fireDate = '01-01-2060 00:00:00';			  // set exact date time | Format: dd-MM-yyyy HH:mm:ss

const alarmNotifData = {
	title: "My Notification Title",
	message: "My Notification Message",
	channel: "my_channel_id",
	small_icon: "ic_launcher",

	// You can add any additional data that is important for the notification
	// It will be added to the PendingIntent along with the rest of the bundle.
	// e.g.
  	data: { foo: "bar" },
};

class App extends Component {
	...

    async method(){
        //Schedule Future Alarm
        const alarm = await ReactNativeAN.scheduleAlarm({ ...alarmNotifData, fire_date: fireDate });
        console.log(alarm); // { id: 1 }

        //Delete Scheduled Alarm
        ReactNativeAN.deleteAlarm(alarm.id);

        //Delete Repeating Alarm
        ReactNativeAN.deleteRepeatingAlarm(alarm.id);

        //Stop Alarm
        ReactNativeAN.stopAlarmSound();

        //Send Local Notification Now
        ReactNativeAN.sendNotification(alarmNotifData);

        //Get All Scheduled Alarms
        const alarms = await ReactNativeAN.getScheduledAlarms();

        //Clear Notification(s) From Notification Center/Tray
        ReactNativeAN.removeFiredNotification(alarm.id);
        ReactNativeAN.removeAllFiredNotifications();
    }

	...
}

Handle notification intent

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

import com.emekalites.react.alarm.notification.BundleJSONConverter;
import com.facebook.react.ReactActivity;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import org.json.JSONObject;
...

public class MainActivity extends ReactActivity {
    ...

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        try {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                JSONObject data = BundleJSONConverter.convertToJSON(bundle);
                getReactInstanceManager().getCurrentReactContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("OnNotificationOpened", data.toString());
            }
        } catch (Exception e) {
            System.err.println("Exception when handling notification opened. " + e);
        }
    }

}

Listener for notifications

import { NativeEventEmitter, NativeModules } from 'react-native';

const { RNAlarmNotification } = NativeModules;
const RNAlarmEmitter = new NativeEventEmitter(RNAlarmNotification);

const dismissSubscription = RNAlarmEmitter.addListener(
    'OnNotificationDismissed', (data) => console.log(JSON.parse(e));
);

const openedSubscription = RNAlarmEmitter.addListener(
    'OnNotificationOpened', (data) => console.log(JSON.parse(e));
);

...

// unsubscribe, typically in componentWillUnmount
dismissSubscription.remove();
openedSubscription.remove();

iOS Permissions

import ReactNativeAN from 'react-native-alarm-notification';

// check if notification permissions has been granted for iOS
ReactNativeAN.checkPermissions((permissions) => {
	console.log(permissions);
});

// Request iOS permissions
ReactNativeAN.requestPermissions({
	alert: true,
	badge: true,
	sound: true,
}).then(
	(data) => {
		console.log('RnAlarmNotification.requestPermissions', data);
	},
	(data) => {
		console.log('RnAlarmNotification.requestPermissions failed', data);
	}
);

Some features are missing

This module is customized to help with scheduling and sending notifications (local) in react-native. A couple of helpful features may be missing but hopefully they can be added as time goes on.

NOTE: If you need a react-native module that takes care of Firebase Cloud Messaging, you could use react-native-firebase

react-native-alarm-notification's People

Contributors

degemenc avatar emekalites avatar jianwen612 avatar josedomingos919 avatar krislm avatar maretana avatar mezalejandro avatar mogol23 avatar phuochoangminhnguyen avatar ridwanmubarok avatar shivamjoker avatar silver292 avatar tehw0lf avatar tensfeld avatar tsanio avatar tuxrace avatar yudican 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

react-native-alarm-notification's Issues

Everyday alarm

The documentation says that you must specify firedate.
Then how to specify only the time and every day?

incompatible types: int cannot be converted to String - ANModule

I got this error while building with 1.4.3:

node_modules/react-native-alarm-notification/android/src/main/java/com/emekalites/react/alarm/notification/ANModule.java:83: error: incompatible types: int cannot be converted to String
            int alarmId = Integer.parseInt(bundle.getInt("alarm_id"));

/node_modules/react-native-alarm-notification/android/src/main/java/com/emekalites/react/alarm/notification/ANModule.java:171: error: incompatible types: int cannot be converted to String
            int alarmId = Integer.parseInt(bundle.getInt("alarm_id"));

Add multiple alarms

Hey i've just started using this library and this worked nicely!

but there was a problem when i tried to add three alarms. It just took the last alarm i made ( the third alarm ). How can i fix it? Thanks.

alarm is not stopping when app is closes

hi , i've made an alarm than stop by itself after 20 seconds
it works only when the app is open. when i am goind outside the app , the alarm doesnt stop at all (only when i come back to the app )
I would like the alarm to have the same behaviour outside and inside the app

react native :0.59.10

export default class App extends React.Component{
  constructor() {
    super();
    this.state = {
      time: "",
      fireDate :'',

    };
  }
  onCancel() {
    this.TimePicker.close();
  }

  insertZero=(main_string,pos,ins_string)=>{
    return main_string.slice(0, pos) + ins_string + main_string.slice(pos);
  }
 
  onConfirm(hour, minute) {

    this.setState({ time: `${hour}:${minute}` });
    this.TimePicker.close()
    
    var date = new Date()
    date.setHours(hour)
    date.setMinutes(minute)
    date.setSeconds('00')
    var dateTimeNow = new Date(Date.now())

    if(dateTimeNow>date){
      date.setHours(date.getHours() + 24)
    }
    if(minute<10){
      var fireDate=this.insertZero(ReactNativeAN.parseDate(new Date(date)),14,'0')
    }
    else{
      var fireDate = ReactNativeAN.parseDate(new Date(date)) 
    }
    fireDate=this.insertZero(fireDate,19,'0')

    const alarmNotifData = {
      id: "12345",                                  // Required
      title: "My Notification Title",               // Required
      message: "My Notification Message",           // Required
      channel: "my_channel_id",                     // Required. Same id as specified in MainApplication's onCreate method
      ticker: "My Notification Ticker",
      auto_cancel: true,                            // default: true
      vibrate: true,
      vibration: 100,                               // default: 100, no vibration if vibrate: false
      small_icon: "ic_launcher",                    // Required
      large_icon: "ic_launcher",
      play_sound: true,
      sound_name: null,                             // Plays custom notification ringtone if sound_name: null
      color: "red",
      schedule_once: true,                          // Works with ReactNativeAN.scheduleAlarm so alarm fires once
      tag: 'some_tag',
      fire_date: fireDate,                          // Date for firing alarm, Required for ReactNativeAN.scheduleAlarm.
   
      // You can add any additional data that is important for the notification
      // It will be added to the PendingIntent along with the rest of the bundle.
      // e.g.
      data: { foo: "bar" },
  };

  var delta = (date-dateTimeNow)+20000;
  ReactNativeAN.scheduleAlarm(alarmNotifData)
  setTimeout(() => {
    ReactNativeAN.stopAlarm()
  }, delta);

}

  render(){
    return(
      <View style={styles.container}>
        <Text style={styles.text}>Shabbat Alarm</Text>

        <TouchableOpacity
          onPress={() => this.TimePicker.open()}
          style={styles.button}
        >
          <Text style={styles.buttonText}>Choose your time</Text>
        </TouchableOpacity>
        <Text style={styles.text}>{this.state.time}</Text>
        <TimePicker
          ref={ref => {
            this.TimePicker = ref;
          }}
          onCancel={() => this.onCancel()}
          onConfirm={(hour, minute) => this.onConfirm(hour, minute)}
        />
        
      </View>
    )
  }
}

ISSUE WITH METHODS...

Hi!!! This is the first time that i used this module...
I have the configuration bellow, the problem is that when i press the button, the scheduleAlarm and others method does not work...:

The error says:

Uncaught Error: undefined is not an object (evaluating 'RNALarmNotification.scheduleAlarm')

I dont know what to do! I also linked and add the part of the xml, and check the .java files. But everything is ok!

Thanks

`

setAlarm = () => {
    const fireDate = new Date(Date.now() + 5000);     // set the fire date for 1 second from now
    const alarmNotifData = {
        id: "12345",                                  // Required
        title: "My Notification Title",               // Required
        message: "My Notification Message",           // Required
        ticker: "My Notification Ticker",
        auto_cancel: true,                            // default: true
        vibrate: true,
        vibration: 100,                               // default: 100, no vibration if vibrate: false
        small_icon: "ic_launcher",                    // Required
        large_icon: "ic_launcher",
        play_sound: true,
        sound_name: null,                             // Plays custom notification ringtone if sound_name: null
        color: "red",
        schedule_once: true,                          // Works with ReactNativeAN.scheduleAlarm so alarm fires once
        tag: 'some_tag',
        fire_date: ReactNativeAN.parseDate(fireDate)  // Date for firing alarm, Required for ReactNativeAN.scheduleAlarm. Format: dd-MM-yyyy HH:mm:ss
    };
    ReactNativeAN.scheduleAlarm(alarmNotifData);
}`

Unable to start receiver com.emekalites.react.alarm.notification.AlarmReceiver

First of all thanks for this amazing library, it works very well but I got this error.

Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'com.facebook.react.bridge.JavaScriptModule com.facebook.react.bridge.ReactApplicationContext.getJSModule(java.lang.Class)' on a null object reference
at com.emekalites.react.alarm.notification.AlarmReceiver.onReceive(AlarmReceiver.java:86)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3700)
at android.app.ActivityThread.access$2000(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1903)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7406)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

[BUG] cannot call [scheduleAlarm/ sendNotification] multiple times

When I try to call scheduleAlarm or sendNotification multiple times like this:

const notificationTpl = {
  // id: '123',
  title: "title",               // Required 
  message: "message",           // Required 
  auto_cancel: false,                            // default: true 
  vibrate: true,                                      
  vibration: 100,                               // default: 100, no vibration if vibrate: false 
  small_icon: "ic_launcher",                    // Required 
  large_icon: "ic_launcher",                          
  play_sound: true,                                    
  sound_name: null,                             // Plays custom notification ringtone if sound_name: null 
  color: "red",                                       
  // schedule_once: true,                          // Works with ReactNativeAN.scheduleAlarm so alarm fires once 
}
ReactNativeAN.sendNotification(notificationTpl)
ReactNativeAN.sendNotification(notificationTpl) 

Got an Error:
You attempted to set the key id with the value "1503550784856" on an object that is meant to be immutable and has been frozen.

Android error new version 1.4.0

When I installed new version on android studio I have the error:
Unsupported Modules Detected: Compilation is not supported for following modules: android-react-native-alarm-notification, react-native-alarm-notification. Unfortunately you can't have non-Gradle Java modules and Android-Gradle modules in one project.

Why substract one month on Alarm fire date ?

Why would you want to substract one month in calendar.set(Calendar.MONTH, alarm.getMonth() - 1); and repeat this action multiple times ?

This action is in ANModule (l. 105) and three times in AlarmUtils (l. 137, 179, 188).

Missing notification dismiss?

I was looking for a way to run something when user dismisses the notification, but I couldn't find one?
Is there some way to do that or is this going to be added at some point?
Here is some related discussion

can not get notification data while app started via notification click

Hi,
Thanks for the useful library. I can not figure out how to get notification data when app is started via local notification. I mean the app is completely closed when the notification is showed up. I tried the "OnNotificationOpened'" event but it is not triggered on startup.

Geting Error during build

Error:Execution failed for task ':react-native-alarm-notification:compileDebugJavaWithJavac'.

Compilation failed; see the compiler error output for details.

[issue] Cannot use the custom sound?

    const testDate = new Date();
    const alarmNotifData = {
      id: '12345', // Required
      title: 'My Notification Title', // Required
      message: 'My Notification Message', // Required
      ticker: 'My Notification Ticker',
      auto_cancel: true, // default: true
      vibrate: true,
      vibration: 100, // default: 100, no vibration if vibrate: false
      small_icon: 'ic_launcher', // Required
      large_icon: 'ic_launcher',
      play_sound: true,
      sound_name: 'meditation.mp3', // Plays custom notification ringtone if sound_name: null
      color: 'red',
      schedule_once: true, // Works with ReactNativeAN.scheduleAlarm so alarm fires once
      tag: 'some_tag',
      fire_date: `23-01-2018 ${testDate.getHours()}:${testDate.getMinutes()}:${testDate.getSeconds() + 2}`, // Date for firing alarm, Required for ReactNativeAN.scheduleAlarm. Format: dd-MM-yyyy HH:mm:ss
    };
    ReactNativeAN.scheduleAlarm(alarmNotifData);

I cannot set the custom sound for my alarm. Even I have followed exactly like the instruction.

Alarm crashes when app is closed

To reproduce

  1. Schedule an alarm.
  2. Close the app before the alarm will set off.
    This should cause a crash when the alarm is triggered.

This is how errors look like from adb logcat:

AndroidRuntime: FATAL EXCEPTION: main
AndroidRuntime: Process: com.nativetest, PID: 2913
AndroidRuntime: java.lang.RuntimeException: Unable to start receiver com.emekalites.react.alarm.notification.ANAlarmReceiver: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.nativetest/com.emekalites.react.alarm.notification.ANService (has extras) }: app is in background uid UidRecord{a75b117 u0a85 RCVR idle change:idle|uncached procs:1 seq(0,0,0)}
AndroidRuntime:        at android.app.ActivityThread.handleReceiver(ActivityThread.java:3388)
AndroidRuntime:        at android.app.ActivityThread.access$1200(ActivityThread.java:199)
AndroidRuntime:        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1661)
AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:106)
AndroidRuntime:        at android.os.Looper.loop(Looper.java:193)
AndroidRuntime:        at android.app.ActivityThread.main(ActivityThread.java:6669)
AndroidRuntime:        at java.lang.reflect.Method.invoke(Native Method)
AndroidRuntime:        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
AndroidRuntime:        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
AndroidRuntime: Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.nativetest/com.emekalites.react.alarm.notification.ANService (has extras) }: app is in background uid UidRecord{a75b117 u0a85 RCVR idle change:idle|uncached procs:1 seq(0,0,0)}
AndroidRuntime:        at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1577)
AndroidRuntime:        at android.app.ContextImpl.startService(ContextImpl.java:1532)
AndroidRuntime:        at android.content.ContextWrapper.startService(ContextWrapper.java:664)
AndroidRuntime:        at android.content.ContextWrapper.startService(ContextWrapper.java:664)
AndroidRuntime:        at com.emekalites.react.alarm.notification.ANAlarmReceiver.onReceive(ANAlarmReceiver.java:20)
AndroidRuntime:        at android.app.ActivityThread.handleReceiver(ActivityThread.java:3379)
AndroidRuntime:        ... 8 more
AudioFlinger: not enough memory for AudioTrack size=131296
AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
IAudioFlinger: createRecord returned error -12
AudioRecord: AudioFlinger could not create record track, status: -12
AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.

One way around seems to be

  1. Trigger the alarm once when the app is running.
  2. Schedule it again to launch after some time.
  3. Close the app before the alarm will set off.
    This seems to not cause crash when the alarm is triggered.

Build Failing after integration

Post following steps and adding to project, build is failing with below error
image

Tried changing the target sdk compile sdk, all above 26, etc, but still getting same error. Any suggestions?

How to use 'react-native-alarm-notification'...

Hi,

Plz provide a demo app to implement 'react-native-alarm-notification' and fire notification even when app is closed means inactive.

How to use 'react-native-alarm-notification' to wakeup the app periodically????...

After setting Alarm and kill the app too will trigger APP STOP pop up at the schedule time

React Native: v 0.57.4

buildToolsVersion = "27.0.3"
minSdkVersion = 19
compileSdkVersion = 27
targetSdkVersion = 26
supportLibVersion = "27.1.1"

Tested on

Samsung J7 Prime 
Android 8.1
import ReactNativeAN from "react-native-alarm-notification";
const fireDate = "21-11-2018 12:33:00";
const alarmNotifData = {
  id: "12345", 
  title: "My Notification Title",
  message: "My Notification Message",
  channel: "islamic1234",
  ticker: "My Notification Ticker",
  auto_cancel: true,
  vibrate: true,
  vibration: 100,
  small_icon: "ic_launcher",
  large_icon: "ic_launcher",
  play_sound: true,
  sound_name: "azan", 
  color: "red",
  schedule_once: true,
  tag: "some_tag",
  fire_date: fireDate, 
  data: { foo: "bar" }
};
componentWillMount() {
    ReactNativeAN.scheduleAlarm(alarmNotifData);
  }

Not Working even example

Good morning,
actually i copyed your example App.js Emulator built it correctly , but when i set a value in input text (example 120 in future time from now ) , or by pressing Sending Notification Now,, always return an error :

null is not an object ( evaluating 'RNAAlarmNotification.scheduleAlarm'

This by working with EXPO.

In normal way , return this (pressing Send notification Now):

Cattura

Can you explain me what i m doing wrong ?

Tyvm

Repeat Sound

Can i repeat the sound until user press a button or something like that?

Running the app on background

Hi, new to react-native and playing around with alarm app.

I managed to let the alarm capability work. However, I am concern if the app can run as background process.

I tried the following:

  1. Open the app
  2. Set up the alarm for 30 seconds later when component is mounted.
  3. Click the home button.
  4. Remove it to the list of recent apps opened.

Sadly, the alarm isn't triggered when I tried removing it to the list of apps. I am trying to achieve something that will let the alarm capability run on background process, same as with the normal phone alarm clock.

Btw, I was using an android emulator.

Can I use the app the same way as I described above? Thanks!

Not working with expo

Library (example from repository) doesn't work with expo.

Screenshot_20190626-013521

Screenshot_20190626-013531

Expo diagnostic output

    System:
      OS: Linux 4.15 Linux Mint 18.3 (Sylvia)
      Shell: 4.3.48 - /bin/bash
    Binaries:
      Node: 10.16.0 - ~/.nvm/versions/node/v10.16.0/bin/node
      Yarn: 1.16.0 - ~/.nvm/versions/node/v10.16.0/bin/yarn
      npm: 6.9.0 - ~/.nvm/versions/node/v10.16.0/bin/npm
      Watchman: 4.9.0 - /usr/local/bin/watchman
    npmPackages:
      expo: ^33.0.0 => 33.0.5 
      react: 16.8.3 => 16.8.3 
      react-native: https://github.com/expo/react-native/archive/sdk-33.0.0.tar.gz => 0.59.8 
    npmGlobalPackages:
      expo-cli: 2.19.5

Example from repository works fine with react-native run-android command.

React-native info output:

React Native Environment Info:
    System:
      OS: Linux 4.15 Linux Mint 18.3 (Sylvia)
      CPU: (8) x64 Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz
      Memory: 1.35 GB / 7.69 GB
      Shell: 4.3.48 - /bin/bash
    Binaries:
      Node: 10.16.0 - ~/.nvm/versions/node/v10.16.0/bin/node
      Yarn: 1.16.0 - ~/.nvm/versions/node/v10.16.0/bin/yarn
      npm: 6.9.0 - ~/.nvm/versions/node/v10.16.0/bin/npm
      Watchman: 4.9.0 - /usr/local/bin/watchman
    SDKs:
      Android SDK:
        API Levels: 28, 29
        Build Tools: 28.0.3, 29.0.0
        System Images: android-28 | Intel x86 Atom_64, android-29 | Google APIs Intel x86 Atom
    npmPackages:
      react: 16.6.3 => 16.6.3 
      react-native: 0.58.1 => 0.58.1 

where can I add the "Listener for notifications"

Where can I add those stuff or a function that run after the notification was open! please I need help with that I've tried to put it in the view file, but the devicemetter is undefined, and i've tried to put it in the main activity file thing which made no sense anyway. please help! thanks!
image

Doesn't work on Android 9

Hi,
I'm using your library since v1.3.1 version.
It didn't work on Android 9 so I forked your repo and updated the code as written on the android developer docs on my android-o-fix branch.

Today I saw that recently you updated your repo to a newer version, so i gave it a try, but still it doesn't work on Android 9.
I looked at the code and noticed that has changed a lot. You did a great job!!

I Hope you can fix it as soon as possible, until then, i'll still use my branch.
Best regards.

Custom sound doesn't repeat

Hi,

I just worked on this one and it's working fine.
But when I tried with custom sound, it only plays once.

So in my case, my sound file is 26 seconds so the alarm only rings for 26 seconds.
I want it to ring until I stop it.

How can I fix this?

ReactNativeAN.deleteAlarm is not working

I have linked everything properly and defined the future alarm with and ID but when i try to delete the alarm , it does nothing. I have tried giving string and integers and even hard coded values for id but still nothing happens.

Key alarm_id expected Integer but value was a java.lang.Double.

I cannot schedule future reminders, I get error output from logcat.

2020-04-05 15:08:40.688 22168-22383/com.timer W/Bundle: Key alarm_id expected Integer but value was a java.lang.Double.  The default value 0 was returned.
2020-04-05 15:08:40.688 22168-22383/com.timer W/Bundle: Attempt to cast generated internal exception:
    java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
        at android.os.BaseBundle.getInt(BaseBundle.java:1041)
        at android.os.BaseBundle.getInt(BaseBundle.java:1023)
        at com.emekalites.react.alarm.notification.ANModule.scheduleAlarm(ANModule.java:83)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:372)
        at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:151)
        at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:27)
        at android.os.Looper.loop(Looper.java:214)
        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:226)
        at java.lang.Thread.run(Thread.java:919)
2020-04-05 15:08:40.689 22168-22383/com.timer E/com.emekalites.react.alarm.notification.ANModule: failed to schedule notification because fire date is missing

Here is my code.

const alarmNotifData = {
	alarm_id: 12345,
	title: "My Notification Title",
	message: "My Notification Message",
	channel: "my_channel_id",
	small_icon: "ic_launcher"
};
ReactNativeAN.scheduleAlarm({...alarmNotifData, fireDate: ReactNativeAN.parseDate(new Date(endDate.current)) });

My package version:
react: 16.11.0
react-native: 0.62.0
react-native-alarm-notification: 1.4.2

No notification and no native alarm

I've gone through all the issues and can't tell why I'm the only one who can't get the alarm to work. If I call all the other methods like cancelAllNotifications(), getScheduledAlarms, I get expected values logged. When I try calling sendNotification and scheduleAlarm, I get neither error nor notification. Also checking my phone's alarm shows nothing was set, meaning it isn't a notifications issue alone. What could the problem be?

I have this at the tail end of my imports


import android.app.NotificationManager;
import android.app.NotificationChannel;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;

And this inside the onCreate method
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);

String id = "bvm_id";          // The id of the channel.
CharSequence name = "BVM";      // The user-visible name of the channel.
String description = "Bible_Memorization_Alarm";  // The user-visible description of the channel.

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT);

  // Configure the notification channel. 
  mChannel.setDescription(description);

  mChannel.enableLights(true);
  // Sets the notification light color for notifications posted to this
  // channel, if the device supports this feature. 
  mChannel.setLightColor(Color.RED);

  mChannel.enableVibration(true);
  mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});

  NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(mChannel);
}

}

I have the following android manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bibleapp">

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

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
      <service android:name="com.emekalites.react.alarm.notification.ANService" android:enabled="true"/>
        <receiver android:name="com.emekalites.react.alarm.notification.ANAlarmReceiver" android:enabled="true"/>
        <receiver android:name="com.emekalites.react.alarm.notification.ANBootReceiver" android:enabled="true" android:exported="true">
            <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>

</manifest>

I linked the package after installing it, and crosschecked with manual linking. The only step I didn't follow is the one in the MainActivity.java file which I can't find imports for. Is that why it doesn't work?

What other info do you need to reproduce the error?
Version 1.2.4

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.