Code Monkey home page Code Monkey logo

cordova-plugin-local-notifications's Introduction

SAMPLE APP 👉

npm version PayPayl donate button License


A notification is a message you display to the user outside of your app's normal UI. When you tell the system to issue a notification, it first appears as an icon in the notification area. To see the details of the notification, the user opens the notification drawer. Both the notification area and the notification drawer are system-controlled areas that the user can view at any time.


Notification components

  • Header area
  • Content area
  • Action area

How notifications may be noticed

  • Showing a status bar icon
  • Appearing on the lock screen
  • Playing a sound or vibrating
  • Peeking onto the current screen
  • Blinking the device's LED

Supported platforms

  • Android 4.4+
  • iOS 10+
  • Windows 10


Important Notice

Please make sure that you always read the tagged README for the version you're using.

See the 0.8 branch if you cannot upgrade. Further development for v0.9-beta will happen here. The 0.9-dev and ios10 branches are obsolate and will be removed soon.

Known issues

  • Support for Android Oreo is limited yet.
  • v0.9 and v0.8 aren't compatible with each other (Wont fix)

Please report bugs or missing features!

Basics

The plugin creates the object cordova.plugins.notification.local and is accessible after deviceready has been fired.

cordova.plugins.notification.local.schedule({
    title: 'My first notification',
    text: 'Thats pretty easy...',
    foreground: true
});

The plugin allows to schedule multiple notifications at once.

cordova.plugins.notification.local.schedule([
    { id: 1, title: 'My first notification' },
    { id: 2, title: 'My first notification' }
]);

Properties

A notification does have a set of configurable properties. Not all of them are supported across all platforms.

Property Property Property Property Property Property Property Property Property
id data timeoutAfter summary led clock channelName actions alarmVolume
text icon attachments smallIcon color defaults launch groupSummary resetDelay
title silent progressBar sticky vibrate priority mediaSession foreground autoLaunch
sound trigger group autoClear lockscreen number badge wakeup channelId
iconType wakeLockTimeout triggerInApp fullScreenIntent

For their default values see:

cordova.plugins.notification.local.getDefaults();

To change some default values:

cordova.plugins.notification.local.setDefaults({
    led: { color: '#FF00FF', on: 500, off: 500 },
    vibrate: false
});

Actions

The plugin knows two types of actions: button and input.

cordova.plugins.notification.local.schedule({
    title: 'The big survey',
    text: 'Are you a fan of RB Leipzig?',
    attachments: ['file://img/rb-leipzig.jpg'],
    actions: [
        { id: 'yes', title: 'Yes' },
        { id: 'no',  title: 'No' }
    ]
});

         

Input

cordova.plugins.notification.local.schedule({
    title: 'Justin Rhyss',
    text: 'Do you want to go see a movie tonight?',
    actions: [{
        id: 'reply',
        type: 'input',
        title: 'Reply',
        emptyText: 'Type message',
    }, ... ]
});

It is recommended to pre-define action groups rather then specifying them with each new notification of the same type.

cordova.plugins.notification.local.addActions('yes-no', [
    { id: 'yes', title: 'Yes' },
    { id: 'no',  title: 'No'  }
]);

Once you have defined an action group, you can reference it when scheduling notifications:

cordova.plugins.notification.local.schedule({
    title: 'Justin Rhyss',
    text: 'Do you want to go see a movie tonight?',
    actions: 'yes-no'
});

Properties

Actions do have a set of configurable properties. Not all of them are supported across all platforms.

Property Type Android iOS Windows
id button+input x x x
title button+input x x x
launch button+input x x x
ui button+input x
needsAuth button+input x
icon button+input x
emptyText input x x x
submitTitle input x
editable input x
choices input x
defaultValue input x

Triggers

Notifications may trigger immediately or depend on calendar or location.

To trigger at a fix date:

cordova.plugins.notification.local.schedule({
    title: 'Design team meeting',
    text: '3:00 - 4:00 PM',
    trigger: { at: new Date(2017, 10, 27, 15) }
});

Or relative from now:

cordova.plugins.notification.local.schedule({
    title: 'Design team meeting',
    trigger: { in: 1, unit: 'hour' }
});

Repeating

Repeat relative from now:

cordova.plugins.notification.local.schedule({
    title: 'Design team meeting',
    trigger: { every: 'day', count: 5 }
});

Or trigger every time the date matches:

cordova.plugins.notification.local.schedule({
    title: 'Happy Birthday!!!',
    trigger: { every: { month: 10, day: 27, hour: 9, minute: 0 } }
});

Location based

To trigger when the user enters a region:

cordova.plugins.notification.local.schedule({
    title: 'Welcome to our office',
    trigger: {
        type: 'location',
        center: [x, y],
        radius: 15,
        notifyOnEntry: true
    }
});

Properties

The properties depend on the trigger type. Not all of them are supported across all platforms.

Type Property Type Value Android iOS Windows
Fix
at Date x x x
Timespan
in Int x x x
unit String second x x x
unit String minute x x x
unit String hour x x x
unit String day x x x
unit String week x x x
unit String month x x x
unit String quarter x x x
unit String year x x x
Repeat
count Int x x
every String minute x x x
every String hour x x x
every String day x x x
every String week x x x
every String month x x x
every String quarter x x
every String year x x x
before Date x x
firstAt Date x x
Match
count Int x x
every Object minute x x x
every Object hour x x x
every Object day x x x
every Object weekday x x x
every Object weekdayOrdinal x
every Object week x
every Object weekOfMonth x x x
every Object month x x x
every Object quarter x
every Object year x x x
before Date x x
after Date x x
Location
center Array [lat, long] x
radius Int x
notifyOnEntry Boolean x
notifyOnExit Boolean x
single Boolean x

Progress

Notifications can include an animated progress indicator that shows users the status of an ongoing operation.

cordova.plugins.notification.local.schedule({
    title: 'Sync in progress',
    text: 'Copied 2 of 10 files',
    progressBar: { value: 20 }
});

Patterns

Split the text by line breaks if the message comes from a single person and just too long to show in a single line.

cordova.plugins.notification.local.schedule({
    title: 'The Big Meeting',
    text: '4:15 - 5:15 PM\nBig Conference Room',
    smallIcon: 'res://calendar',
    icon: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTzfXKe6Yfjr6rCtR6cMPJB8CqMAYWECDtDqH-eMnerHHuXv9egrw'
});

Summarizing

Instead of displaying multiple notifications, you can create one notification that summarizes them all.

cordova.plugins.notification.local.schedule({
    id: 15,
    title: 'Chat with Irish',
    icon: 'http://climberindonesia.com/assets/icon/ionicons-2.0.1/png/512/android-chat.png',
    text: [
        { message: 'I miss you' },
        { person: 'Irish', message: 'I miss you more!' },
        { message: 'I always miss you more by 10%' }
    ]
});

To add a new message to the existing chat:

cordova.plugins.notification.local.update({
    id: 15,
    text: [{ person: 'Irish', message: 'Bye bye' }]
});

Grouping

Your app can present multiple notifications as a single group:

  • A parent notification displays a summary of its child notifications.
  • The child notifications are presented without duplicate header information.
cordova.plugins.notification.local.schedule([
    { id: 0, title: 'Design team meeting', ... },
    { id: 1, summary: '[email protected]', group: 'email', groupSummary: true },
    { id: 2, title: 'Please take all my money', ... group: 'email' },
    { id: 3, title: 'A question regarding this plugin', ... group: 'email' },
    { id: 4, title: 'Wellcome back home', ... group: 'email' }
]);

Permissions

Each platform may require the user to grant permissions first before the app is allowed to schedule notifications.

cordova.plugins.notification.local.hasPermission(function (granted) { ... });

If requesting via plug-in, a system dialog does pop up for the first time. Later its only possible to tweak the settings through the system settings.

cordova.plugins.notification.local.requestPermission(function (granted) { ... });

Checking the permissions is done automatically, however it's possible to skip that.

cordova.plugins.notification.local.schedule(toast, callback, scope, { skipPermission: true });

On Android 8, special permissions are required to exit "do not disturb mode" (in case alarmVolume is defined). You can check these by using:

cordova.plugins.notification.local.hasDoNotDisturbPermissions(function (granted) { ... })

... and you can request them by using:

cordova.plugins.notification.local.requestDoNotDisturbPermissions(function (granted) { ... })

The only downside to not having these permissions granted is that alarmVolume and vibrate may not be honored on Android 8+ devices if the device is currently on silent when the notification fires (silent, not vibrate). In this situation, the notification will fire silently but still appear in the notification bar.

Also on Android 8, it is helpful for alarms that autolaunch the app with an event, if the app can ignore battery saving mode (otherwise alarms won't trigger reliably). You can check to see if the app is whitelisted for this with the following method.

cordova.plugins.notification.local.isIgnoringBatteryOptimizations(function (granted) { ... })

... and you can request to be whitelisted by using:

cordova.plugins.notification.local.requestIgnoreBatteryOptimizations(function (granted) { ... })

The request method here will work one of two ways.

  1. If you have the REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission defined in the manifest, it will use ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS to explicitly ignore battery optimizations for this app. This is the best overall user experience, but the REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission seems to be frowned upon and can get your app banned. This plugin does not have this permission in plugin.xml for this reason, so you will need to use the cordova-custom-config plugin to add it to your config.xml
  2. If you do not have REQUEST_IGNORE_BATTERY_OPTIMIZATIONS requested, it will launch ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS to show a list of all applications. You will want to put some sort of instructions prior to this to walk the user through this. Also, this action doesn't exist on all Android devices (is missing on Samsung phones), which will make this method simply return false if it can't start the activity.

Events

The following events are supported: add, trigger, click, clear, cancel, update, clearall and cancelall.

cordova.plugins.notification.local.on(event, callback, scope);

To unsubscribe from events:

cordova.plugins.notification.local.un(event, callback, scope);

Note: You have to provide the exact same callback to cordova.plugins.notification.local.un as you provided to cordova.plugins.notification.local.on to make unsubscribing work. Hence you should define your callback as a separate function, not inline. If you want to use this inside of your callback, you also have to provide this as scope to cordova.plugins.notification.local.on.

Custom

The plugin also fires events specified by actions.

cordova.plugins.notification.local.schedule({
    title: 'Do you want to go see a movie tonight?',
    actions: [{ id: 'yes', title: 'Yes' }]
});

The name of the event is the id of the action.

cordova.plugins.notification.local.on('yes', function (notification, eopts) { ... });

Fire manually

Not an official interface, however its possible to manually fire events.

cordova.plugins.notification.local.core.fireEvent(event, args);

Launch Details

Check the launchDetails to find out if the app was launched by clicking on a notification.

document.addEventListener('deviceready', function () {
    console.log(cordova.plugins.notification.local.launchDetails);
}, false);

It might be possible that the underlying framework like Ionic is not compatible with the launch process defined by cordova. With the result that the plugin fires the click event on app start before the app is able to listen for the events.

Therefore its possible to fire the queued events manually by defining a global variable.

window.skipLocalNotificationReady = true

Once the app and Ionic is ready, you can fire the queued events manually.

cordova.plugins.notification.local.fireQueuedEvents();

Methods

All methods work asynchronous and accept callback methods. See the sample app for how to use them.

Method Method Method Method Method Method
schedule cancelAll isTriggered get removeActions un
update hasPermission getType getAll hasActions fireQueuedEvents
clear requestPermission getIds getScheduled getDefaults requestDoNotDisturbPermissions
clearAll isPresent getScheduledIds getTriggered setDefaults hasDoNotDisturbPermissions
cancel isScheduled getTriggeredIds addActions on

Installation

The plugin can be installed via Cordova-CLI and is publicly available on NPM.

Execute from the projects root folder:

$ cordova plugin add cordova-plugin-local-notification

Or install a specific version:

$ cordova plugin add cordova-plugin-local-notification@VERSION

Or install the latest head version:

$ cordova plugin add https://github.com/katzer/cordova-plugin-local-notifications.git

Or install from local source:

$ cordova plugin add <path> --nofetch --nosave --link

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

License

This software is released under the Apache 2.0 License.

Made with 😋 from Leipzig

© 2013 appPlant GmbH

cordova-plugin-local-notifications's People

Contributors

0x1ad2 avatar akuraru avatar alecaddd avatar davidtron avatar dpalou avatar dpogue avatar extempl avatar ginovva320 avatar gittothehub avatar idanb11 avatar jokiamo avatar katzer avatar khizarsonu avatar kumarsunil0007 avatar luca-itro avatar michelreij avatar pataar avatar pknittel avatar richsage avatar rwillett avatar silvioq avatar spk0611 avatar tedyk avatar timkellyert avatar timkellypa avatar uareurapid avatar vaenow avatar wootwoot1234 avatar ygpedroso avatar zfoltin 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  avatar  avatar

cordova-plugin-local-notifications's Issues

Notification detail view is a mostly empty screen

I can create a notification without problems, it displays in my device's notification bar/ notification list, and looks like other notifications from other apps. However, when I click on the notification I get a black screen with only the app name and icon in it, my text isn't displayed and I don't seem to be able to put any content in it. I then have to click the device's back button to see my app again.

Is there some way I can skip this notification detail view entirely, or get more control over what is displayed in it? When I click on the notification I would prefer to have the background / foreground fire, and then go straight to my app.

Thanks for any help!

When i click the notification for second time myapp doesn't show up

Hi, with the new version 0.6.2, when myapp is on background and sends a notification, when i click on the notification it opens myapp the first time, but if i press the home button again and then click again in the notification i get nothing, or sometimes i get myapp name on top with a black screen after that if i press home and click again i still get the black screen, but if i press back when the black screen is on i get sent to the desktop, i click again on the notification it opens up myapp again. I have a backup with the previous plugin and it works fine, everytime i click on the notification it brings my app up. And i have included in AndroidManifest.xml android:launchMode="singleInstance" in the activity section. Thanks in advance.

not working for android phonegap 3.0

Hi Katzer,

i was trying to install the plugin but it is not working on emulator or real device
the logcat says:

Uncaught ReferenceError: device is not defined at file:///android_asset/www/plugins/de.appplant.cordova.plugin.local-notifications/www/local-notification.js:32

can you please help,

Best Regards,

Basta

iOS default type error

Thanks for doing all this work and letting me use it.

The documentation example:
window.plugin.notification.local.add({ message: 'Great app!' });

Didn't work for me on iOS in the simulator, until I added 'id:1' in the example call, or more robustly, changed defaults= id:0 to id:'0' in local-notification.js.

Looks like a type error, when "id" defaults to 0 it is an integer, and crashes in the compare code that casts it to a string:
(BOOL) strIsNullOrEmpty:(NSString*)str

Christmas wish list for v0.7.0

  • auto cancel feature
  • custom repeat interval
  • redesign callbacks (ontrigger & onclick)
  • exec onclick/background callback even app is not running yet
  • less bugs
  • more pull requests

Scope of callback functions

Hi.

I've noticed that if I declare my callbacks inside an anonymous function I can a "foreground is undefined" exception

 (function(){
    function foreground () {
       // ...
    }

    window.plugin.notification.local.add({
        id: "1",
        message: 'text',
        foreground: 'foreground'
    });
 }());

If I declare the callbacks globally, they work fine, like

 function foreground () {
     // ...
  }

 (function(){

    window.plugin.notification.local.add({
        id: "1",
        message: 'text',
        foreground: 'foreground'
    });
 }());

This is a bit problematic for my application design, as I would prefer not to have too many functions cluttering global. Is there something I'm missing here? Why are the callbacks defined as strings? Could we not pass the callbacks in directly like

    window.plugin.notification.local.add({
        id: "1",
        message: 'text',
        foreground: function(){
            // 
        }
    });

Thanks.

Android icon notification

Hello,

Thanks for porting this plugin to phonegap3

It works great on android but i'm wondering the best way to put a custom icon for the notification.

Currently i see this way: in LocalNotificationOptions.java , i need to change this line with my custom png (ic_launcher):

public int getIcon () {
    return options.optInt("icon", R.drawable.ic_launcher);
}

But in order to works well, i need to fix the import to:

import $MY_PACKAGE_NAME.R;

And this operation need to be done manually after the installation of the plugin.. for each upgrade ....

What do you think? Is there a better way?

Close notification on click

Hi, a nice feature would be an option(or a flag), to let us decide if we want to keep the notification when clicked, or dismiss the notification (on android).
BTW i don't know how to put labels and Thanks for all your hard work.

delivery of local notifications on android when app not running.

Thanks for your help. I believe things mostly work as they should now. However there are still a couple of issues and one problem.

First, to simplify testing, I modified LocalNotification.java with the following (currently android only):

if (repeat.equalsIgnoreCase("quarterly")) {
        interval = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
} else if (repeat.equalsIgnoreCase("hourly")) {
        interval = AlarmManager.INTERVAL_HOUR;
} else if (repeat.equalsIgnoreCase("daily")) {
        interval = AlarmManager.INTERVAL_DAY;
    } else if (repeat.equalsIgnoreCase("weekly")) {

This allows to schedule local notifications more frequently to test how my app handles certain sequences of events.

I still have the problem that (repeated) local notifications are not delivered when the app is not running, for instance after a reboot. I have been looking on the internet, this seems by design on android. Is there a convenient way to make sure that these notifications are also delivered after a reboot? I am pretty ignorant regarding android development, so any pointers or help is greatly appreciated.
Thanks,
Hugo

App crashes when setting a notification on Android 2.2

When a notification is set on Android 2.2 the application force closes. This is immediately after calling:

window.plugin.notification.local.add();

In Eclipse I can see this error:

01-07 09:26:31.015: E/dalvikvm(8751): Could not find class 'android.app.Notification$Builder', referenced from method de.appplant.cordova.plugin.localnotification.Receiver.buildNotification

Here is the whole error report:

01-07 09:26:31.015: E/dalvikvm(8751): Could not find class 'android.app.Notification$Builder', referenced from method de.appplant.cordova.plugin.localnotification.Receiver.buildNotification
01-07 09:26:31.015: D/MobileDataStateTracker(1339): replacing old mInterfaceName (rmnet0) with rmnet0 for supl
01-07 09:26:31.015: W/dalvikvm(8751): VFY: unable to resolve new-instance 18 (Landroid/app/Notification$Builder;) in Lde/appplant/cordova/plugin/localnotification/Receiver;
01-07 09:26:31.015: D/dalvikvm(8751): VFY: replacing opcode 0x22 at 0x0000
01-07 09:26:31.025: D/dalvikvm(8751): VFY: dead code 0x0002-0046 in Lde/appplant/cordova/plugin/localnotification/Receiver;.buildNotification ()Landroid/app/Notification$Builder;
01-07 09:26:31.025: I/dalvikvm(8751): Could not find method android.app.Notification$Builder.setContentIntent, referenced from method de.appplant.cordova.plugin.localnotification.Receiver.setClickEvent
01-07 09:26:31.025: W/dalvikvm(8751): VFY: unable to resolve virtual method 69: Landroid/app/Notification$Builder;.setContentIntent (Landroid/app/PendingIntent;)Landroid/app/Notification$Builder;
01-07 09:26:31.025: D/dalvikvm(8751): VFY: replacing opcode 0x6e at 0x0030
01-07 09:26:31.025: D/dalvikvm(8751): VFY: dead code 0x0033-0034 in Lde/appplant/cordova/plugin/localnotification/Receiver;.setClickEvent (Landroid/app/Notification$Builder;)Landroid/app/Notification$Builder;
01-07 09:26:31.025: I/dalvikvm(8751): Could not find method android.app.Notification$Builder.getNotification, referenced from method de.appplant.cordova.plugin.localnotification.Receiver.showNotification
01-07 09:26:31.025: W/dalvikvm(8751): VFY: unable to resolve virtual method 68: Landroid/app/Notification$Builder;.getNotification ()Landroid/app/Notification;
01-07 09:26:31.035: D/dalvikvm(8751): VFY: replacing opcode 0x6e at 0x001b
01-07 09:26:31.035: I/dalvikvm(8751): Could not find method android.app.Notification$Builder.build, referenced from method de.appplant.cordova.plugin.localnotification.Receiver.showNotification
01-07 09:26:31.035: W/dalvikvm(8751): VFY: unable to resolve virtual method 67: Landroid/app/Notification$Builder;.build ()Landroid/app/Notification;
01-07 09:26:31.035: D/dalvikvm(8751): VFY: replacing opcode 0x6e at 0x0029
01-07 09:26:31.035: D/dalvikvm(8751): VFY: dead code 0x001e-0021 in Lde/appplant/cordova/plugin/localnotification/Receiver;.showNotification (Landroid/app/Notification$Builder;)V
01-07 09:26:31.035: D/dalvikvm(8751): VFY: dead code 0x002c-0030 in Lde/appplant/cordova/plugin/localnotification/Receiver;.showNotification (Landroid/app/Notification$Builder;)V

Android Notification console.log not showing

Hi katzer,

am I missing out something else, did follow the examples and cordova added the plugins. But theres no log from the notification plugin. It shows error on "Uncaught TypeError: Cannot read property 'notification' of undefined"

GPL license

This plugin looks extremely useful, however I am working on a project that is not in a position to make use of it because of the copyleft requirements of GPLv2 (one of the main reasons we selected Cordova is because it is Apache licensed and so placed no such restrictions).

Is there any possibility that you would consider relaxing the license or dual-licensing (e.g. LGPL/MIT/BSD)? As a point for consideration, I understand that there are potential issues distributing GPL projects via the iOS App Store which might limit the audience for this plugin (google VLC App Store, for example)

(Please understand that I entirely understand if you don't wish to switch from pure GPL - it's your choice. I hate to ask at all but I'm restricted from GPL by various commercial agreements)

Thanks for your work!

Can't cancel notification by id

Hi I found that I can't remove the notification by ID

I was doing this like:
window.plugin.notification.local.add({
id:1,
date: minsFromNow
});

window.plugin.notification.local.cancel('1');

is that correct? I think it is better to have a example on it in the docs, thanks:)

Handle iOS notification limit

The apple documentation is mentioning a limit:

Each application on a device is limited to 64 scheduled local notifications.
The system discards scheduled notifications in excess of this limit, keeping
only the 64 notifications that will fire the soonest.

Is this handled in your plugin?

I can see you are using a function archiveNotification to keep a copy of each notification but I did not see any kind of update function to refill the iOS notification buffer. In my old plugin there was this update function. Maybe you like to add some similar:

- (void)updateActiveNotifications:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options {

    // internal queue
    [self loadQueue];

    // sort queue by date
    NSSortDescriptor *sortDescriptor;
    sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"fireDate" ascending:YES] autorelease];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    NSArray *sortedArray = [self.queue sortedArrayUsingDescriptors:sortDescriptors];
    self.queue = [NSMutableArray arrayWithArray:sortedArray];

    // remove old messages, where fireDate is in past
    NSDate* currentDate = [NSDate date];
    BOOL moreToDelete = YES;
    while (moreToDelete && [self.queue count] > 0) {
        UILocalNotification* toCheck = [self.queue objectAtIndex:0];
        if ([currentDate compare:toCheck.fireDate] == NSOrderedDescending ) {
            [self.queue pop];
            //UILocalNotification* deleted = [self.queue pop];
            //NSLog(@"Notification Deleted - ID: %@ fireDate: %@", [deleted.userInfo objectForKey:@"notificationId"], deleted.fireDate);
        } else {
            moreToDelete = NO;
        }
    }
    NSLog(@"Queue holds %u Notifications", [self.queue count]);

    // delete all active notifications
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    NSLog(@"Activ Notificaions cleaned");

    // loop over first 64 message and send them to active notification
    for (int i = 0; i < [self.queue count] && i < 65; i++) {
        UILocalNotification* toAdd = [self.queue objectAtIndex:i];
        [[UIApplication sharedApplication] scheduleLocalNotification:toAdd];
        //NSLog(@"Notification Added - ID: %@ text: %@ fireDate: %@", [toAdd.userInfo objectForKey:@"notificationId"], toAdd.alertBody, toAdd.fireDate);
    }

    // DEBUG: check active notify
    NSArray *notifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
    NSLog(@"%u new active Notifications have been added", [notifications count]);
    //for (UILocalNotification *notification in notifications) {
    //  NSString *notId = [notification.userInfo objectForKey:@"notificationId"];
    //
    //    NSLog(@"active Notification: ID: %@ text: %@ fireDate %@ ", notId, notification.alertBody, notification.fireDate);
    //}

    // store queue
    [self loadQueue];

    NSLog(@"Update active Notifications - done");
}

Update

I see you are using the archiv only for cancelAll. I think you could just call [[UIApplication sharedApplication] cancelAllLocalNotifications]; here.

Notification redirect to the certain action

Hi, first of all... thank you a lot for this plugin... this is exactly what i was looking for!

But i have a question... i am new to phonegap and android apps and i would like to do a certain action when the user opens the app by clicking on the notification ... is that possible please?

i would like to attach a vibration signal to the notification but i dont know how.

"navigator.notification.vibrate(2000);" i can put this code next to the "window.plugin.notification.local.add" but this will not work when the notification is set up to the specific time... it would be great if there would be some callback function or something like: "foreground: 'app.foreground' " but : "active": 'some_function' or something.

Thx

Documentation is wrong

the method "clear" and "clearAll" should be "cancel" & "cancelAll", the doc is written wrongly.

Java Integer.getInteger() method

I had problems with the Integer.getInteger() method in Options.java/parse(). The configuration with a repeat interval of a chosen number minutes did not work. I tracked it down to the invocation of the above mentioned method.

To solve the issue, I replaced the code in the file Options.java:

    } else {
        interval = Integer.getInteger(repeat, 0) * 60000;
    }

with

    } else {
        interval = Integer.parseInt(repeat) * 60000;
    }

This seems to work properly.

I will look into contributing code using git pull / push for future issues.
Thanks.

Submit this plugin to phonegap build

After reading about this plugin and the platforms it supports, it seems very promising, and I would like to use it. However I am a phonegap build user, and I do not have a local phonegap environment.

I think that a lot of PGB users would benefit from this plugin. The only way for us to use it is for it to be submitted to phonegap build.

From what I understand, as long as the plugin is open source, anyone can submit it. But I think one would need a local phonegap environment to do so (?). Also, not sure if the author prefers to submit it himself (probably best since it would link directly to the github repository).

Restore Android notifications with minimum date value of current datetime

I'm wondering what your thoughts are about changing the notification restore process on Android to make sure that any notifications that hadn't fired while the device was off get restored with a minimum of the current datetime when the device is rebooted. This would ensure that no local notifications are missed, which currently occurs.

This change would match the behaviour on iOS (which that OS handles for us).

Edit: I'll note that I've already made this change for myself and would be willing to submit a PR. Just wanted to check first.

Repeat with shorter intervals

Currently, for repeat we only have the options daily, weekly, monthly, yearly. But I would find it very useful to have the possibility to repeat with shorter intervals, for example hourly or even every 'x' number of minutes.
Would this be possible?

Android background notification not performing events on click.

Hi,

I'm using the plugin on my local phonegap android build (v3.2) application. So far, the application is generating and displaying the notifications properly.

When the application is in the foreground, the foreground callback I have written executes correctly. (Side-note: I have only been able to cancel the notification in the foreground by using setTimeout() with the cancel() method. Is this normal?)

To test the background callback, I perform the event that adds the notification, and then quickly close the app. Five seconds later, the notification appears in the status bar, as expected.

The problem is that when I click on the notification, the app simply restarts, but the background callback is not called. So all I see is the starting screen for my app. (But thanks to the new auto-cancel clause, the notification does disappear, a great addition!)

Am I mis-using the background callback? I tried adding the launch mode "singleInstance" clause to the main activity in the AndroidManifest.xml file, but this makes no impact whatsoever whether or not it is there.

Can you help me resolve this matter?

Thanks.

Future notification will be cancelled when cancel run twice or multiple times.

Let's say I run this:

window.plugin.notification.local.cancelAll();
window.plugin.notification.local.cancelAll();

and then I add in a new notification:

window.plugin.notification.local.add({
id:1,
date: minsFromNow,
message: "Duha completed. 5 minutes break has automatically started.",
sound:'www/sound/done.caf',
autoCancel:true
});

the notification won't come out.

compiler error

Hi,

Great plugin. Worked well on my android emulator and device so far.

I believe I was hit with one of the bugs that was recently fixed, wrt notifications on Android when the app is running in the background.

So after upgrading the plugin with 'plugin rm' and then 'plugin add', I got the following error:

-compile:
[javac] Compiling 18 source files to /home/hugo/neurospaces_project/jokes-on-you/source/snapshots/0/cordova/jokes-on-you/platforms/android/bin/classes
[javac] /home/hugo/neurospaces_project/jokes-on-you/source/snapshots/0/cordova/jokes-on-you/platforms/android/src/de/appplant/cordova/plugin/localnotification/LocalNotification.java:213: non-static variable this cannot be referenced from a static context
[javac] if (this.context == null) {
[javac] ^
[javac] /home/hugo/neurospaces_project/jokes-on-you/source/snapshots/0/cordova/jokes-on-you/platforms/android/src/de/appplant/cordova/plugin/localnotification/LocalNotification.java:214: non-static variable this cannot be referenced from a static context
[javac] this.context = context;
[javac] ^
[javac] Note: /home/hugo/neurospaces_project/jokes-on-you/source/snapshots/0/cordova/jokes-on-you/platforms/android/src/org/apache/cordova/datepicker/Datepicker.java uses or overrides a deprecated API.
[javac] Note: Recompile with -Xlint:deprecation for details.
[javac] 2 errors
',
'
I am currently stuck.

Any idea?

Thanks for the help, thanks for a great plugin.

Hugo

Icon notification on Android

Hi,
i'm not able to change the icon notification into my app icon...

My index.js:
(...)
window.plugin.notification.local.add({ message: 'Great app!', icon: 'icon'});
(...)

My AndroidManifext.xml:
(...)

(...)

Work only icons under android.R.drawable ("android.R.drawable...."), for example window.plugin.notification.local.add({ message: 'Great app!', icon: 'ic_dialog_map'}) works fine.

What is the mistake?
How can I see the app icon in the notification?

Adding multiple notifications, with different dates, triggers them all at once

First, I want to thank you for this plug-in, it is exactly what I need for my application (all of the other notification plug-ins work by using GCM and I don't think my application calls for that)

The notifications push to my device fairly well. However, my application calls for seven notifications to be called in a semi-random fashion throughout a day. I figured that I could add these seven notifications upon a user opening their application by passing seven randomly incremented times to these notifications--all at once, at the opening of the application-- but instead of the notifications occuring at their assigned times, they are all called at once at one of their assigned times.

Here is a picture of the drop down notifications-- note how the times in the messages are all the same, when they should all be 60 seconds apart from one another:

notification_err

Here are my calls to the plugin to test queuing multiple notification calls:

 function addNotificationNow(){
        var now              = new Date().getTime(),
        _60_seconds_from_now = new Date(now + 60*1000),
        _120_seconds_from_now = new Date(_60_seconds_from_now + 60*1000),
        _180_seconds_from_now = new Date(_120_seconds_from_now + 60*1000);

        window.plugin.notification.local.add({
            id:         1, // is converted to a string
            title:      'E-Cigarette Survey Reminder',
            message:    'Tap to open up the survey application',
            repeat:     'daily',
            badge:      1,
            foreground: 'foreground',
            background: 'background'
        });

        window.plugin.notification.local.add({
            id:         2, // is converted to a string
            date:       _60_seconds_from_now,
            title:      'E-Cigarette Survey Reminder',
            message:    _60_seconds_from_now.toString(),
            repeat:     'daily',
            badge:      2,
            foreground: 'foreground',
            background: 'background'
        });
        window.plugin.notification.local.add({
            id:         3, // is converted to a string
            date:       _120_seconds_from_now,
            title:      'E-Cigarette Survey Reminder',
            message:    _120_seconds_from_now.toString(),
            repeat:     'daily',
            badge:      3,
            foreground: 'foreground',
            background: 'background'
        });
        window.plugin.notification.local.add({
            id:         4, // is converted to a string
            date:       _180_seconds_from_now,
            title:      'E-Cigarette Survey Reminder',
            message:    _180_seconds_from_now.toString(),
            repeat:     'daily',
            badge:      4,
            foreground: 'foreground',
            background: 'background'
        });
    }

I imagine that this error has something to do with the asynchronous nature of javascript. Unfortunately I am inexperienced with an asynchronous language such as this and I am not sure how to remedy my situation. I know that this is a place to report issues and not solutions to our individual problems, but I am unaware of a workaround. Is there currently a way to call multiple notifications in a day, at set times?

0.6.3 on Phonegap Build

I noticed that yesterday a 0.6.3 release was created here, but on PGB I still see 0.6.2. I'm not too familiar with the process; is the update waiting for PGB approval? (in which case I can go bug them about it).

Thanks!

Minimum Android SDK version 11 (3.0)

I'm not 100% sure of this, but it seems this plugin only supports Android 3.0 due to using Notification.Builder (SDK 11+). If this is the case, would you please add a note with the Android version requirement to your README?

Thanks!

reopen app problem,is it a Android terrible problem?

ios,ipad mini 7.04
Android,HTC Sensation XL 4.03

when I call this methoid,window.plugin.notification.local.add({ message: 'Great app!' });

in ios, the status bar show the notification,and I click it(the notification message will "disappear"),it will "reback" to the original app,seems everything is OK

but in Android,the status bar show the notification too,and I click it(the notification message will "not disappear"),it will "reopen" another the original app(because of when I click it,it will show the splashscreen and do some initial function again),when I close the another the original app,it seems will "reback" to the original app,just like this address,Then the screen does not move, except when I press the Back or Home button
http://www.littlebau.com/reopen.png

Missing background callback

Missing implementation to exec the callback function if the app is in background and a notification is clicked.

Cancel single notification does not work

window.plugin.notification.local.cancel does not work (maybe it does not pass on the string). cancelAll() on the other hand works.

var id = '12';
window.plugin.notification.local.cancel(id);

Thank you for the plugin by the way.

How do i add custom sound

I have a alert.wav in my www folder and i have
sound:'alert.wav' in my function
i get the notifications fine but it doesn't plays my custom alert.wav

Sencha Touch integration

Hi,

I'm trying to integrate this plugin in to a Cordova based Sencha Touch app but when compiling it is causing an error when trying to load the necessary files of your plugin.

From what I can work out, it is looking for two files, APPLocalNotification.m and APPLocalNotification.o but they cannot be found. Other Cordova plugins work as expected and compile properly.

I have also posted this on Sencha's forum if you'd like a bit more explanation http://www.sencha.com/forum/showthread.php?279613-Native-build-plugin-dependancy-problem

Question on Repeat

Firstly,

I think your example is wrong it has:
repeat: 'Dont forget to buy some flowers.',
I think that should be message or something?

My actual question is how does the repeat property work? Do you set a date and then it repeats at that date/time depending on how the repeat is set? Ex. If is set it for 8:00am tomorrow, does it repeat at 8am everyday if I set it to "daily"?

Thanks. Looks like a very helpful plugin.

I cannot use v0.6.3 on phonegap build

this plguin is really very nice. but i got some bugs on v0.6.2.
like black screen on android. so i use the v0.6.3.
when I add the v0.6.3 in my config.xml and zip my folder to build on the phonegap build.
<gap:plugin name="de.appplant.cordova.plugin.local-notification" version="0.6.3" />
it will get error " plugin unsupported: de.appplant.cordova.plugin.local-notification 0.6.3 ".
i noticed that the plugin version here(https://build.phonegap.com/plugins/331 ) was still 0.6.2.
so how can i use the v0.6.3 ?
thanks.

After Removing from Recent App List

Hi katzer,

Please help me. I found problem when i remove app from Recent App List from Nexus 7.

I found error(Logcat)

11-24 20:52:18.288: D/AndroidRuntime(840): Shutting down VM
11-24 20:52:18.288: W/dalvikvm(840): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-24 20:52:18.307: E/AndroidRuntime(840): FATAL EXCEPTION: main
11-24 20:52:18.307: E/AndroidRuntime(840): java.lang.RuntimeException: Unable to start receiver de.appplant.cordova.plugin.localnotification.LocalNotificationReceiver: java.lang.NullPointerException
11-24 20:52:18.307: E/AndroidRuntime(840): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2236)
11-24 20:52:18.307: E/AndroidRuntime(840): at android.app.ActivityThread.access$1500(ActivityThread.java:130)
11-24 20:52:18.307: E/AndroidRuntime(840): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1271)
11-24 20:52:18.307: E/AndroidRuntime(840): at android.os.Handler.dispatchMessage(Handler.java:99)
11-24 20:52:18.307: E/AndroidRuntime(840): at android.os.Looper.loop(Looper.java:137)
11-24 20:52:18.307: E/AndroidRuntime(840): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-24 20:52:18.307: E/AndroidRuntime(840): at java.lang.reflect.Method.invokeNative(Native Method)
11-24 20:52:18.307: E/AndroidRuntime(840): at java.lang.reflect.Method.invoke(Method.java:511)
11-24 20:52:18.307: E/AndroidRuntime(840): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-24 20:52:18.307: E/AndroidRuntime(840): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-24 20:52:18.307: E/AndroidRuntime(840): at dalvik.system.NativeStart.main(Native Method)
11-24 20:52:18.307: E/AndroidRuntime(840): Caused by: java.lang.NullPointerException
11-24 20:52:18.307: E/AndroidRuntime(840): at de.appplant.cordova.plugin.localnotification.LocalNotificationOptions.getIcon(LocalNotificationOptions.java:120)
11-24 20:52:18.307: E/AndroidRuntime(840): at de.appplant.cordova.plugin.localnotification.LocalNotificationReceiver.buildNotification(LocalNotificationReceiver.java:101)
11-24 20:52:18.307: E/AndroidRuntime(840): at de.appplant.cordova.plugin.localnotification.LocalNotificationReceiver.onReceive(LocalNotificationReceiver.java:62)
11-24 20:52:18.307: E/AndroidRuntime(840): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2229)
11-24 20:52:18.307: E/AndroidRuntime(840): ... 10 more

Thank You
Sandip

App crash Android, NullPointer Exception after clicking on a Notification when application was in background

Hello,

I attached a local notification and closed the app completely. When it comes back through clicking on the notification the entire application crashes:

W/dalvikvm( 5776): threadid=11: thread exiting with uncaught exception (group=0x415cdba8)
W/System.err( 5776): java.lang.NullPointerException
W/System.err( 5776):    at de.appplant.cordova.plugin.localnotification.ReceiverActivity$1.run(ReceiverActivity.java:91)
W/System.err( 5776):    at java.util.Timer$TimerImpl.run(Timer.java:284)
W/FlurryAgent( 5776): Error logged: uncaught
W/FlurryAgent( 5776): Ending session
V/GmsNetworkLocationProvi(  999): onSetRequest: ProviderRequestUnbundled, reportLocation is true and interval is 60000
V/GmsNetworkLocationProvi(  999): SET-REQUEST
V/GmsNetworkLocationProvi(  999): in Handler: ProviderRequestUnbundled, reportLocation is true and interval is 60000
E/AndroidRuntime( 5776): FATAL EXCEPTION: Timer-0
E/AndroidRuntime( 5776): Process: de.myapp.app,´, PID: 5776
E/AndroidRuntime( 5776): java.lang.NullPointerException
E/AndroidRuntime( 5776):    at de.appplant.cordova.plugin.localnotification.ReceiverActivity$1.run(ReceiverActivity.java:91)
E/AndroidRuntime( 5776):    at java.util.Timer$TimerImpl.run(Timer.java:284)
W/ActivityManager(  609):   Force finishing activity de.myapp.app/.App

Can you help me with that?

It is not working on android

I installed it and it is working on iOS, but is not on android;

it produced no error in the code, but the notification doesn't come out as well, any idea?

My environment is cordova 3.1 and android 4.2

Thanks!

This is the error log:

10-29 17:06:53.590: W/System.err(5981): java.lang.ClassNotFoundException: de.appplant.cordova.plugin.LocalNotification
10-29 17:06:53.590: W/System.err(5981): at java.lang.Class.classForName(Native Method)
10-29 17:06:53.590: W/System.err(5981): at java.lang.Class.forName(Class.java:217)
10-29 17:06:53.590: W/System.err(5981): at java.lang.Class.forName(Class.java:172)
10-29 17:06:53.590: W/System.err(5981): at org.apache.cordova.PluginEntry.getClassByName(PluginEntry.java:117)
10-29 17:06:53.590: W/System.err(5981): at org.apache.cordova.PluginEntry.createPlugin(PluginEntry.java:93)
10-29 17:06:53.590: W/System.err(5981): at org.apache.cordova.PluginManager.getPlugin(PluginManager.java:267)
10-29 17:06:53.590: W/System.err(5981): at org.apache.cordova.PluginManager.execHelper(PluginManager.java:221)
10-29 17:06:53.590: W/System.err(5981): at org.apache.cordova.PluginManager.exec(PluginManager.java:216)
10-29 17:06:53.590: W/System.err(5981): at org.apache.cordova.ExposedJsApi.exec(ExposedJsApi.java:53)
10-29 17:06:53.590: W/System.err(5981): at android.webkit.JWebCoreJavaBridge.sharedTimerFired(Native Method)
10-29 17:06:53.590: W/System.err(5981): at android.webkit.JWebCoreJavaBridge.sharedTimerFired(Native Method)
10-29 17:06:53.590: W/System.err(5981): at android.webkit.JWebCoreJavaBridge.fireSharedTimer(JWebCoreJavaBridge.java:92)
10-29 17:06:53.590: W/System.err(5981): at android.webkit.JWebCoreJavaBridge.handleMessage(JWebCoreJavaBridge.java:108)
10-29 17:06:53.590: W/System.err(5981): at android.os.Handler.dispatchMessage(Handler.java:99)
10-29 17:06:53.590: W/System.err(5981): at android.os.Looper.loop(Looper.java:137)
10-29 17:06:53.590: W/System.err(5981): at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:812)
10-29 17:06:53.590: W/System.err(5981): at java.lang.Thread.run(Thread.java:856)
10-29 17:06:53.600: W/System.err(5981): Caused by: java.lang.NoClassDefFoundError: de/appplant/cordova/plugin/LocalNotification
10-29 17:06:53.600: W/System.err(5981): ... 17 more
10-29 17:06:53.600: W/System.err(5981): Caused by: java.lang.ClassNotFoundException: Didn't find class "de.appplant.cordova.plugin.LocalNotification" on path: /data/app/com.dink.mha2013-2.apk
10-29 17:06:53.600: W/System.err(5981): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
10-29 17:06:53.600: W/System.err(5981): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
10-29 17:06:53.600: W/System.err(5981): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
10-29 17:06:53.600: W/System.err(5981): ... 17 more
10-29 17:06:53.600: I/System.out(5981): Error adding plugin de.appplant.cordova.plugin.LocalNotification.
10-29 17:06:53.600: D/PluginManager(5981): exec() call to unknown plugin: LocalNotification

Failing cancel a notification with string id

I got this error when I tried to cancel my notification which has string as an id. java.lang.NumberFormatException: Invalid int: "abc"
In LocalNotification.java:141, there is this line:
nc.cancel(Integer.parseInt(notificationId));
The cancel notification required an Integer as id eventhough id add methode, id is a string

android: local sound file is not played

Thanks for this great plugin! However, I encountered one issue with Android: When I specify a custom notification sound, it works OK when I specify a sound file on a remote location, i.e. sound: 'http://example.com/sound.mp3'
But when I specify a local sound file it doesn't work. No sound, no error messages either. My sound file is located in the top www directory. I tried many ways to specify the location, but nothing works:
sound: 'sound.mp3'
sound: '/sound.mp3'
sound: 'www/sound.mp3'
sound: '/www/sound.mp3'
sound: 'android_asset/www/sound.mp3'
sound: '/android_asset/www/sound.mp3'
sound: 'file://sound.mp3'
sound: 'file:///sound.mp3'
sound: 'file://www/sound.mp3'
sound: file:///www/sound.mp3'
sound: 'file://android_asset/www/sound.mp3'
sound: 'file:///android_asset/www/sound.mp3'

I this a bug, or am I doing something wrong? Please advise

  • thanks, Allard

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.