Multiple notification using Local Notification plugin - Phonegap - android

Katzer Local notification plugin
I can set and use single notification.
According to the description mutiple notification can be set using
cordova.plugins.notification.local.schedule([{
id: 1,
text: "Multi Notification 1",
sound: isAndroid ? 'file://sound.mp3' : 'file://beep.caf',
data: { secret:key }
},{
id: 2,
title: "Local Notification Example",
text: "Multi Notification 2",
icon: "http://sciactive.com/pnotify/includes/github-icon.png"
}]);
But my notifications are dynamic and it's total number is also dynamic. For example say total is the variable where total number of notification is saved. total can be 1 or 10 or 30 etc.
Now how to build the array for it?? I tried like this
for(i=0;i<total;i++)
{
// ......... calculate bhhour,vmin,vsec etc. ............. //
time_for_noti=new Date(year,month-1,parseInt(i),vhour,vmin,vsec);
arr[i]=' id: app_'+i+' , title: ' +i+' - '+time_for_noti+',text: app alarm.,sound: null,at : '+time_for_noti+' ';
}
And then
cordova.plugins.notification.local.schedule(arr);
App hangs for some time say 15-20 sec, then crashes. Then I tried brackets '{}' before and after the strings.
for(i=0;i<total;i++)
{
// ......... calculate bhhour,vmin,vsec etc. ............. //
time_for_noti=new Date(year,month-1,parseInt(i),vhour,vmin,vsec);
arr[i]='{ id: app_'+i+' , title: ' +i+' - '+time_for_noti+',text: app alarm.,sound: null,at : '+time_for_noti+' }';
}
Again same result. App crashes after 10-15 sec from schedule line's execution. I also tried making a huge string manually something like
ex='[{ id:........} , {..........}]';
And then
cordova.plugins.notification.local.schedule(ex);
It crashes the app immediately after this line's execution. I know it's a dumb idea, but desperate times.
What I'm doing wrong? How to achive this multiple alarm dynamically for total 20-40 notification? What I'm missing?

I think each element in the array needs to be an object, not a string. Have you tried something like this?
arr[i]={ id: i, text: "Multi Notification " + i };
That is, replace the quote marks around your object with curly brackets.
I can't try it myself because I'm using the Meteor version which doesn't seem to work the same way.

no need to add multiple notification.
I've looped the sound of 1 notification until user clicks on it.
and to give more alarm like feature I bring the app to foreground when notification is triggered.
have a look at https://github.com/vasani-arpit/cordova-plugin-local-notifications/blob/master/README.md. it is forked from Katzer Local notification plugin so all the syntax is the same.

Here is my solution and it works well :
var notiflist = [];
for(var i = 0; i < data.length; i++) {
notiflist[i] = { id: i, title: data[i].Title, text: data[i].TextPush };
}
cordova.plugins.notification.local.schedule(notiflist);

Related

FCM push notification to reawaken app not effective while device slept

I ran into a problem with my flutter app where when it's minimized or the phone is put to sleep for too long (~5+ minutes), the app stops listening to firestore changes. One solution that I came across was to send push notifications to reawaken the device. While it seems to have fixed minimizing problem (the app now responds to changes), however it still suffers from the sleep problem. I noticed that the app still receives the push notifications, but the screen doesn't light up upon receiving them. Could that be why? Is there something that I can do to force the app to connect to the internet? I'm trying to think of a solution like sending a data payload to change the data locally, but I'm not sure if that's the optimal approach (or if it would even work). I'll post my firebase cloud function for sending messages on a doc update:
exports.sendLobbyNotificationTest = functions.firestore
.document("Lobbies/{lobbyCode}")
.onUpdate((change) => {
console.log("Checking for need of push notification...");
// const oldValue = change.before.data() || {};
const newValue = change.after.data() || {};
if (newValue.pushNotification == true) {
console.log("Found a push notification request for: ",
newValue.lobbyCode, "!");
// Set lobby back to false
admin.firestore().collection("Lobbies")
.doc(newValue.lobbyCode).update({
pushNotification: false,
});
return admin.messaging().sendToTopic(newValue.lobbyCode, message)
.then((result) => {
console.log("Message sent successfully: ", result);
// usersRef.where("lobbyCode", "==", newValue.lobbyCode).get()
// .then(function(querySnapshot) {
// querySnapshot.forEach(function(doc){
// })
// })
}).catch((err) => {
console.error("Error sending message: ", err);
});
}
console.log("No message needs to be sent!");
// return dummy value to prevent error
return 0;
});
const message = {
notification: {
title: "Bzzzt!",
body: "You've been buzzed!",
},
};
Is there something I'm missing?
Update: I think it just doesn't work because the phone is locked, once unlocked it begins to function normally.
I think figured out why from reading here: https://developer.android.com/training/monitoring-device-state/doze-standby.html (I had trouble finding this).
Basically if I use the right priority settings for android and ios (priority & content_available) it will bring the app out of idle and listen for changes.

Endless loop in dialogflow v2 detectIntent after having split one input query in two queries

Per default, Dialogflow can only match one intent per one one input:
e.g
User asks: "How are you?"
Dialogflow Agent responds: "I am feeling good!"
(Matched intent: intents.howareyou)
But as soon as the user asks two questions in one input, the agent can not match multiple intents. Only one intent is matched with a smaller confidence interval)
e.g
User asks: "How are you? Do we want to go shopping?"
Dialogflow Agent responds: "Yes, lets go shopping!"
(Matched intent: intents.shopping)
There are two options now to enable the agent to answer both questions in one input:
Create an intent and let the agent response exactly for these two questions.
=> This is a very bad solution, as soon as you add more possible questions/intents. Then you would need to create every combination of every question.
Split the one input into several queries and let the agent perform the intent matching again on the splitted query.
=> This is the preferred way
Based on some blogs in the internet (e.g. https://docs.meya.ai/docs/handle-multiple-intents-in) the second option is what I did.
The Default Fallback Intent is set to use the Fulfillment webhook and this a small part of code executed:
function parseMultipleIntents (agent) {
const query = agent.query;
var pattern= /(.+?[!.?]+)/gm;
var match = pattern.exec(query);
while (match !== null) {
console.log(match[0]);
handleQuery(match[0]); //<----
match = pattern.exec(query);
}
}
The handleQuery method is the actual method, where the splitted queries are handled:
function handleQuery(query){
console.log(query);
// The path to identify the agent that owns the created intent.
const sessionPath = sessionClient.sessionPath("PROJECT_ID", "FIXED_SESSION_ID");
const request = {
session: sessionPath,
queryInput: {
text: {
text: query,
languageCode: 'de',
},
},
};
sessionClient
.detectIntent(request)
.then(responses => {
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
})
.catch(err => {
console.error('ERROR:', err);
});
}
The problem:
If I comment everything in the handleQuery method except console.log(query); then the console outpuut in the firebase console looks fine:
originalQuery: und?warum?
11:39:58.240 PM dialogflowFirebaseFulfillment warum?
11:39:58.238 PM dialogflowFirebaseFulfillment und?
But as soon as I uncomment the rest of the handleQuery and the code looks like above, I get the following console messages which is not stopping. The messages go one if I scoll up in the console. It seems like some kind of loop:
-
-
Do I use detectIntent correctly or do you had such experiences? Or can you spot an issue?
I presumed issues with sync/async calls and also added Promises, but the same happened...
Thanks

Parse.com push notifications lags and duplications

I integrated parse push notifications two days ago and it was working perfect. Today I made some more tests and I have huge lags, like parse notification was coming after 30 minutes instead of up to 5 seconds in previous days.
In addition I have 4 devices and I received 11 "Pushes Sent" instead of 4.
After a while of testing it starts to work normally, with only 4 "Pushes Sent", and after up to one minute instead of 30.
In addition I get 5 times the same push on my developer device, where I am installing and uninstalling app frequently and 4 times on the other dev device, so it sums up to magic number 11.
Is there are known issues with lags on Parse? I need responses up to one minutes. I though that it is reliable service. It was temporary situation or this is normal?
Every time you uninstall and install the app, you get a new installation object. Unfortunately, the old Installation object never goes away. What you need to do is to use some unique identifier for the device and just update the Installation if it exists.
For example, let's say that you're trying to do this on Android.
In your app, you can get the device's ANDROID_ID and save it to the installation: `
ParseInstallation.getCurrentInstallation().put("uniqueId",
Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID));
Then you can have a cloud function that is triggered every time a new installation is saved:
Parse.Cloud.beforeSave(Parse.Installation, function(request, response) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.Installation);
query.equalTo("uniqueId", request.object.get("uniqueId"));
query.first().then(function(duplicate) {
if (typeof duplicate === "undefined") {
console.log("Duplicate does not exist,New installation");
response.success();
} else {
console.log("Duplicate exist..Trying to delete " + duplicate.id);
duplicate.destroy().then(function(duplicate) {
console.log("Successfully deleted duplicate");
response.success();
}, function() {
console.log(error.code + " " + error.message);
response.success();
});
}
}, function(error) {
console.warn(error.code + error.message);
response.success();
});
})
P.S. I've had that function for a long time and can't remember where I got it from, but I did not write it myself.

Error adding Dataset in Smartface App Studio and about local.notifications

I am first mobile application developing on Smartface App Studio. I have tho question.
1- I see this error: Access violation at address 00000000. Read of address 00000000 when add second Dataset. And does not run application on emulator or usb real phone until delete Dataset.
2- I read Local.Notifications guide but could not run notifications on phone screen. I saved dates to table but can not make them as reminder. Which page should i add the function block and how should i do this.
Thanks.
It seems a problem is occured when adding a Dataset. Did you try with a second project ? It seems working with the latest version of Smartface App Studio which downloadable via Account page.
Local Notifications are not added to the calendar/reminder. These are app specific notifications.
First off all, you should create a local notification.
For example;
var localNotification = new Notifications.LocalNotification({
id : id,
fireDate : new Date(),
alertTitle : "AlertTitle",
alertBody : "Alert Body",
smallIcon : "icon_notification_small.png",
launchImage : "icon_notification.png",
sound : "notifsound.mp3",
repeatInterval : Notifications.CalendarUnit.minute,
onReceivedNotification : function (e) {
alert("onReceived");
}
});
It creates a notification for you and it works at given date.
If you want to immaediately show the notification , you should run that code below;
Notifications.local.presentNotification(localNotification);

Error with PushPlugin when the App is in background

I'm trying to implement a push notification app created with Cordava 3.3 using this: https://github.com/phonegap-build/PushPlugin ; Basing me in this tutorial: www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql
But I have 2 basic problems the first is that the notification does not lead if the app is in background or is closed and the second is that the message reaches Undefined when the app is open in the foreground, could help, as far as I was reading may be due the format of the JSON response or parameters sent in the same.
Here is my code not take long:
https://github.com/jedidas/Push
I achieved a solution that is on file with the plugin "GCMIntentService.java" near line 80 is the next instruction
else {
extras.putBoolean("foreground", false);
// Send a notification if there is a message
if (extras.getString("message") != null && extras.getString("message").length() != 0) {
createNotification(context, extras);
}
}
discover you can change the "price" for what you want, for example change the "price" for "message" and everything was solved milagorsamente, explain:
we have this:
. 1 $ message = array ("deprive" => $ message);
and read when I read it as:
1. E.payload.message
gives us comes as undefined because payload.price.
In this sense, we have to file in the JAVA plugin
if (extras.getString ("message")! = null && extras.getString ("message"). length ()! = 0) {
                     createNotification (context, options);
                 }
if that does not run because it is coming as "price" instead of "message". everything is solved when I change the "price" of SEND_MESSAGE.PHP for "message." thus not even need to modify the JAVA.

Categories

Resources