infobip phonegap plugin crash - android

I'm using infobip to deliver push notifications to my apps and i have to admit that it is really powerful.
Anyways i've got a question. Does the cordova plugin work properly? Because my app doesn't recognize the push object (obviously the plugin is installed).
Another question, Must I initialize the plugin in a .js file in all the html page of my app or is enough to call the initialize and register method only in the first .js that the app loads? (index.js for me)
These are some code rows
var senderId1 = "", applicationId1, applicationSecret1;
function notificationListener(event, notification){
switch(event){
case ("onNotificationReceived"):
alert(notification.title);
break;
case ("onInvisibleNotificationReceived"):
// TODO your code here
break;
case ("onNotificationOpened"):
window.location.href = "promo.html";
break;
case ("onUnregistered"):
// TODO your code here
break;
case ("onRegistered"):
// TODO your code here
break;
case ("onError"):
// TODO your code here
break;
default:
// TODO your code here
break;
}
};
//inside the 'onDevideReady' function
if (getMobileOperatingSystem() == 'Android') {
senderId1 = "012345";
applicationId1 = "djdjdjdjdjdj";
applicationSecret1 = "0123456789abcd";
} else {
applicationId1 = "djdjdjdjdjdj";
applicationSecret1 = "0123456789abcd";
push.setBackgroundLocationUpdateModeEnabled(true);
}
//pushnotification
push.initialize(notificationListener);
var text = '{' +
'"regData": {' +
' "applicationId": "' + applicationId1 + '",' +
' "applicationSecret": "' + applicationSecret1 + '",' +
' "senderId": "' + senderId1 + '"' +
'}' +
'}';
var regData = JSON.parse(text);
push.register(regData);
push.enableLocation();
The error i had in xCode is (unfortunately i can't upload an image :( )
#import <UIKit/UIKit.h>
int main(int argc, char* argv[])
{
#autoreleasepool {
int retVal = UIApplicationMain(argc, argv, nil, #"AppDelegate"); //ERROR HERE
return retVal;
}
}
I need to publish this app as soon as possible so thanks for the help.
EDIT:
I change a little my code
plug = window.localStorage.getItem("enable");
alert(plug);
if (plug == null) {
//pushnotification
push.initialize(notificationListener());
alert('here');
if (getMobileOperatingSystem() == 'Android') {
senderId1 = "902945349798";
applicationId1 = "ftscfg8eb5kr";
applicationSecret1 = "qowk5x0q93a30az";
} else {
applicationId1 = "ftscfg8eb5kr";
applicationSecret1 = "qowk5x0q93a30az";
//enable the background location
push.setBackgroundLocationUpdateModeEnabled(true);
}
alert('here2');
/*
var text = '{' +
'"regData": {' +
' "applicationId": "' + applicationId1 + '",' +
' "applicationSecret": "' + applicationSecret1 + '",' +
' "senderId": "' + senderId1 + '"' +
'}' +
'}';
var regData = JSON.parse(text);
*/
//register the push
push.register({
senderId: senderId1,
applicationId: applicationId1,
applicationSecret: applicationSecret1
});
alert('here3');
//enable the location
push.enableLocation();
window.localStorage.setItem('enable', '1');
alert('here4');
}
So, in this case i save a local variable and only if it's the first time i launch the app i set the push parameters. All the alerts works fine and the app works...but i can't receive the notification :(
function notificationListener (event, notification){
switch(event){
case ("onNotificationReceived"):
alert(notification.title);
break;
case ("onInvisibleNotificationReceived"):
// TODO your code here
break;
case ("onNotificationOpened"):
window.location.href = "promo.html";
break;
case ("onUnregistered"):
// TODO your code here
break;
case ("onRegistered"):
// TODO your code here
break;
case ("onError"):
// TODO your code here
alert(notification);
break;
default:
// TODO your code here
break;
}
};
This is my function. When i send a notification using infobip's panel the event OnNotificationreceived will activate...but it's not like this. Even onError doesn't work and the senderID, applicationID and applicationsecret are correct.

Maybe you have to wait for ios is ready.
I initialized the plugin this way:
document.addEventListener("deviceready", initInfoBitPlugin, false);
It works for me.

It should be enough to initialize plugin only once.
Do you get onError event in your notification listener? What do you get as a argument there?
In onNotificationReceived, what is the type of notification argument? Could you JSON.stringify it to logs?
Can you send some logs surrounding this issue?

Related

How to add a skip-ad button to exoplayer with IMA extention using react-native-video

Update:
After much research I've asked this question instead. It gets to the core of the problem. Google IMA webview is not showing when used inside react native on android
We are using react-native-video to use the exoplayer on android to show video with adds. The problem is, the exoplayer doesn't show the skip-button when an ad is skippable. To solve this problem we need to know if an ad is skippable and show a custom skipp-button. That's where I'm stuck. I can't get access to this information without changing the sourcecode of the exoplayer ima-extention.
The preferred solution would be to change the ImaAdsLoader**.onAdEvent() to broadcast an event when the add is loaded that exposes the Ad that has been loaded. Then monitor the playback-progress and show/hide a custom skipp-button.
Is there a way to get the information without altering the code of the ima-extention?
#Override
public void onAdEvent(AdEvent adEvent) {
AdEventType adEventType = adEvent.getType();
boolean isLogAdEvent = adEventType == AdEventType.LOG;
if (DEBUG || isLogAdEvent) {
Log.w(TAG, "onAdEvent: " + adEventType);
if (isLogAdEvent) {
for (Map.Entry<String, String> entry : adEvent.getAdData().entrySet()) {
Log.w(TAG, " " + entry.getKey() + ": " + entry.getValue());
}
}
}
if (adsManager == null) {
Log.w(TAG, "Dropping ad event after release: " + adEvent);
return;
}
Ad ad = adEvent.getAd();
switch (adEvent.getType()) {
case LOADED:
//This line is what I need
eventListener.onAdLoaded(ad);
// The ad position is not always accurate when using preloading. See [Internal: b/62613240].
AdPodInfo adPodInfo = ad.getAdPodInfo();
int podIndex = adPodInfo.getPodIndex();
adGroupIndex = podIndex == -1 ? adPlaybackState.adGroupCount - 1 : podIndex;
int adPosition = adPodInfo.getAdPosition();
int adCountInAdGroup = adPodInfo.getTotalAds();
adsManager.start();
if (DEBUG) {
Log.d(TAG, "Loaded ad " + adPosition + " of " + adCountInAdGroup + " in ad group "
+ adGroupIndex);
}
adPlaybackState.setAdCount(adGroupIndex, adCountInAdGroup);
updateAdPlaybackState();
break;
case CONTENT_PAUSE_REQUESTED:
// After CONTENT_PAUSE_REQUESTED, IMA will playAd/pauseAd/stopAd to show one or more ads
// before sending CONTENT_RESUME_REQUESTED.
imaPausedContent = true;
pauseContentInternal();
break;
case STARTED:
if (ad.isSkippable()) {
focusSkipButton();
}
break;
case TAPPED:
if (eventListener != null) {
eventListener.onAdTapped();
}
break;
case CLICKED:
if (eventListener != null) {
eventListener.onAdClicked();
}
break;
case CONTENT_RESUME_REQUESTED:
imaPausedContent = false;
resumeContentInternal();
break;
case ALL_ADS_COMPLETED:
// Do nothing. The ads manager will be released when the source is released.
default:
break;
}
}

voice sms in cordova android

We are working on hydrid apps. Recently we got the requirement to support voice sms. We did R&D on that but we didn't have any luck. So we are trying to record 1 minute voice then we send it to a server. We don't know is it correct way. Please guide to us.
We tried like this https://www.npmjs.com/package/cordova-plugin-audio-recorder-api
var recorder = new Object;
function stop(){
recorder.stop = function() {
window.plugins.audioRecorderAPI.stop(function(msg) {
// success
alert('ok: ' + msg);
}, function(msg) {
// failed
alert('ko: ' + msg);
});
}}
function record{
recorder.record = function() {
window.plugins.audioRecorderAPI.record(function(msg) {
// complete
alert('ok: ' + msg);
}, function(msg) {
// failed
alert('ko: ' + msg);
}, 30); // record 30 seconds
}}
function playback(){
recorder.playback = function() {
window.plugins.audioRecorderAPI.playback(function(msg) {
// complete
alert('ok: ' + msg);
}, function(msg) {
// failed
alert('ko: ' + msg);
});
}}
We please guide to proper way to achieve our task.

redirect user to a particular page after recieving notification in ngcordova push ionicframework android

is there a way with ionic to bring the user to a specific page or tab when opening the app through the notification?
I send the push,my phone is in background and the user accesses the app tapping on the notification just arrived. Actually the app opens the page which is already opened, but I want it opens a destination page chosen by notification.
// ------------------------------ GCM NG-CORDOVA PUSH-----------------------------------
.run(function($ionicPlatform,ngFB,$state,$cordovaPush,$rootScope,$ionicScrollDelegate, $cordovaMedia) {
$ionicPlatform.ready(function() {
var androidConfig = {
"senderID": "XXXXXXXXXXX"
};
$cordovaPush.register(androidConfig).then(function(result) {
// Success
// alert(result);
}, function(err) {
// Error
alert(err);
});
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
//alert(notification.event);
switch(notification.event) {
case 'registered':
if (notification.regid.length > 0 ) {
// alert('registration ID = ' + notification.regid);
}
break;
case 'message':
$ionicScrollDelegate.$getByHandle('chatScroll').scrollBottom();
// this is the actual push notification. its format depends on the data model from the push server
//alert('message = ' + notification.message + ' msgCount = ' + notification.msgcnt);
alert(JSON.stringify(notification));
if (notification.foreground)
{
// if the notification contains a soundname, play it.
var soundfile = notification.soundname;
// if the notification contains a soundname, play it.
var media = $cordovaMedia.newMedia("/assets/www/"+ soundfile);
media.play();
alert(notification.payload.message);
}
else
{
window.location = '#/home';
//$state.go('home');
}
break;
case 'error':
alert('GCM error = ' + notification.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
});
// WARNING: dangerous to unregister (results in loss of tokenID)
// $cordovaPush.unregister(options).then(function(result) {
// Success!
//}, function(err) {
// Error
//})
});
})
Please Help me. Where i am doing wrong?

When click status bar Notification (Phonegap PushPlugin) The application is launched but does not detect coldstart state

I am developing an android application in eclipse and I have successfully installed the Phonegap PushPlugin, everything works perfectly, notifications are received and launched in the status bar and they open my application when touched.
The problem comes when my application is off (meaning coldstate) , the application is launched successfully but does not run the action inside the "if ( e.coldstart )"
I wrote my code based on the following example published in the official documentation of the plugin:
function onNotificationGCM(e) {
$("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>');
switch (e.event) {
case 'registered':
if (e.regid.length > 0) {
$("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>");
// Your GCM push server needs to know the regID before it can push to this device
// here is where you might want to send it the regID for later use.
console.log("regID = " + e.regid);
}
break;
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
if (e.foreground) {
$("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</li>');
// if the notification contains a soundname, play it.
var my_media = new Media("/android_asset/www/" + e.soundname);
my_media.play();
} else { // otherwise we were launched because the user touched a notification in the notification tray.
if (e.coldstart) {
$("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>');
} else {
$("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>');
}
}
$("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>');
$("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>');
break;
case 'error':
$("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>');
break;
default:
$("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');
break;
}
}
This code is on the main page of my application that opens when you tap the notification and successfully show labels "INLINE NOTIFICATION" and "BACKGROUND NOTIFICATION" whichever is applicable
Not supposed to so place within the
if (e.coldstart) {
$("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>');
}
should be executed if the app comes from being turned off?
would greatly appreciate your cooperation because my application should open a page distinct from index.html when notifications arrive and this is staying in the index.html
Here I'll edit my question to place a text fragment in the original plugin documentation refers to the variable "coldstart":
Finally, should you completely exit the app by hitting the back button
from the home page, you may still receive a notification. Touching
that notification in the notification tray will relaunch your app and
allow you to process the notification (COLDSTART). In this case the
coldstart flag will be set on the incoming event.
Also add my own code that opens a new page when receiving a push-notification:
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent();
},
// Update DOM on a Received Event
receivedEvent: function() {
var pushNotification = window.plugins.pushNotification;
pushNotification.register(app.successHandler, app.errorHandler,{"senderID":"My sender ID","ecb":"app.onNotificationGCM"});
},
// result contains any message sent from the plugin call
successHandler: function(result) {
alert('Callback Success! Result = '+result)
},
errorHandler:function(error) {
alert(error);
},
onNotificationGCM: function(e) {
switch( e.event )
{
case 'registered':
if ( e.regid.length > 0 )
{
console.log("Regid " + e.regid);
window.localStorage.setItem("gcmid", e.regid);
}
break;
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
if ( e.foreground )
{
alert('foreground message = '+e.message+' msgcnt = '+e.msgcnt+' room= '+e.payload.room_msg+' lat = '+lat_r+' lng = '+lng_r);
top.location.href="chat.html?idu=notapply&room_snd=notapply&roomname_snd=" + e.payload.room_msg + "&lat_snd=" + lat_r + "&lng_snd=" + lng_r + "&msg_snd=" + e.message;
}
else
{ // otherwise we were launched because the user touched a notification in the notification tray.
if ( e.coldstart )
{
alert('foreground message = '+e.message+' msgcnt = '+e.msgcnt+' room= '+e.payload.room_msg+' lat = '+lat_r+' lng = '+lng_r);
top.location.href="chat.html?idu=notapply&room_snd=notapply&roomname_snd=" + e.payload.room_msg + "&lat_snd=" + lat_r + "&lng_snd=" + lng_r + "&msg_snd=" + e.message;
}
else
{
alert('foreground message = '+e.message+' msgcnt = '+e.msgcnt+' room= '+e.payload.room_msg+' lat = '+lat_r+' lng = '+lng_r);
top.location.href="chat.html?idu=notapply&room_snd=notapply&roomname_snd=" + e.payload.room_msg + "&lat_snd=" + lat_r + "&lng_snd=" + lng_r + "&msg_snd=" + e.message;
}
}
break;
case 'error':
alert('GCM error = '+e.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
}
};
Solve my problem temporarily adding an additional payload which indicates to my activity which should open a page distinct from index.html, although the solution does not make "e.coldstart" is passed as "true," I add that to function in PushHandlerAtivity.java:
After:
private void forceMainActivityReload()
{
PackageManager pm = getPackageManager();
Intent launchIntent = pm.getLaunchIntentForPackage(getApplicationContext().getPackageName());
startActivity(launchIntent);
}
Before:
private void forceMainActivityReload()
{
PackageManager pm = getPackageManager();
Intent launchIntent = pm.getLaunchIntentForPackage(getApplicationContext().getPackageName());
Bundle extras = getIntent().getExtras();
launchIntent.putExtra("room_msg", extras.getString("room_msg"));
startActivity(launchIntent);
}
of course in the function that generates the notification use addDataWithKeyValue function to add additional payload, then my main activity add the following:
Bundle extras = getIntent().getExtras();
String message = extras.getString("room_msg");
if(message != null){
super.loadUrl("file:///android_asset/www/chat.html?", 10000);
}else{
super.loadUrl("file:///android_asset/www/index.html", 10000);
}
My english is not good. To ensure PushPlugin working good, you should have a test case in Java to make sure plugin run correct or you have a mistake. When you touch in notification, PushHandlerActivity will be call, a it call function:
private void processPushBundle(boolean isPushPluginActive)
{
Bundle extras = getIntent().getExtras();
if (extras != null) {
Bundle originalExtras = extras.getBundle("pushBundle");
originalExtras.putBoolean("foreground", false);
originalExtras.putBoolean("coldstart", !isPushPluginActive);
PushPlugin.sendExtras(originalExtras);
}
}
to identify your app in background or app is closed( in case it fired coldstart-->true)
Edit 1: coldstart true when your app is closed(not in background) and you click into notification to lauch app. When your app in background then coldstart still false. You can hack code by change variable 'isPushPluginActive'=true in above function.
May be this can solve your problem
https://github.com/phonegap-build/PushPlugin/issues/179

How to download and save a file using phonegap/cordova on Android

I am at my whit's end.
I will try to keep it brief.
Using Cordova/Phonegap 3.0 (and get the same results on 2.8.0).
Android version 4.0.4.
Code works on BlackBerry10 (Q10 and Z10).
On Android it errors with a JSON Error (no, I'm not parsing JSON, this seems to come out of cordova's bowels). I will paste the JSON.stringified error object at the end of this.
So, on to code then:
First a filesystem success function:
function onFSSuccess(fileSystem) {
if (fileSystem == null) {
window.alert("fileSystem is null");
}
var root = fileSystem.root;
root.getDirectory("com.app.id",{create:true},gotDir,onError);};
Then a function to handle success with directory retrieval:
function gotDir(d){
DATADIR = d;
doTheDl (d.fullPath + "/update.sql",fileTransfer);
};
Then the actual call to get the filesystem:
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSSuccess, null);
Then a function to download the file:
function doTheDl (localPath,fileTransfer) {
try {
window.alert ("Downloading to '" + localPath + "'");
fileTransfer.download (
uri,
localPath,
function (entry) {
try {
$("#dbDownloadProgressContainer").text("File saved to " + entry.name + ". Applying script to database...");
dbInitObj.applyUpdateScript(entry);
}
catch (e) {
window.alert ( e);
}
},
function (err) {
window.alert ("ERROROR!!! - " + err);
var errCodeName = err.code;
switch (err.code) {
case FileTransferError.FILE_NOT_FOUND_ERR:
errCodeName ='FILE_NOT_FOUND_ERR';
break;
case FileTransferError.INVALID_URL_ERR:
errCodeName="INVALID_URL_ERR";
break;
case FileTransferError.CONNECTION_ERR:
errCodeName="CONNECTION_ERR";
break;
case FileTransferError.ABORT_ERR:
errCodeName="ABORT_ERR";
break;
default:
errCodeName = "UNKNOWN";
break;
}
window.alert ("Download failed: " + err.source + ", " + err.target + ", " + errCodeName);
},
true
);
}
catch (e) {
window.alert ( e);
}
}
Man, gotta love all these async callbacks...
Next we get to the heart of the matter, trying to READ the downloaded file:
//Bulk of applyUpdateScript script ommited, but eventually it gets here:
function readComplete (evt) {
$("#dbDownloadProgressContainer").text("Parsing script file...");
//Got this gem from here: http://beckism.com/2010/09/splitting-lines-javascript/
var lines = evt.target.result.match(/^.*([\n\r]+|$)/gm);
//var lineIndx = lines.length;
window.setTimeout(function () {
$("#dbDownloadProgressContainer").text("Processing " + lines.length + " statements");
},50);
};
try {
var fileReader = new FileReader();
fileReader.onloadend=readComplete;
fileReader.onerror=function (err) {
//var errStr = translateFileError (err);
window.alert ("FileReader.onerror: " +JSON.stringify (err));
};
fileReader.onloadstart=function (evt) {
window.alert ("FileReader.onloadstart - " + JSON.stringify (evt));
};
fileReader.onload=function (evt)
{
window.alert ("FileReader.onload - Called when the read has successfully completed.- " + JSON.stringify (evt));
};
fileReader.onprogress = function (evt)
{
window.alert ("FileReader.onprogress - " + JSON.stringify (evt));
}
fileReader.onabort = function (evt)
{
window.alert ("FileReader.onabort - " + JSON.stringify (evt));
}
function gotFile (fileEntry) {
window.alert ("Activating reader for file '" + fileEntry.fullPath + "'");
fileReader.readAsText(fileEntry);
};
function noFileFound (fileError) {
alert ("Can not access database update script: code " + translateFileError (fileError));
};
// window.alert ("scriptPath.name = " + scriptPath.name);
DATADIR.getFile (scriptPath.name,null,gotFile,noFileFound);
}
catch (e) {
window.alert (e);
}
NOW, when I hit the reading bits, I eventually get this from the 'onerror' event (rember this is the JSON.stringfied error object:
{
"type":"error",
"bubbles":false,
"cancelBubble":false,
"cancelable":false,
"lengthComputable":false,
"loaded":0,
"total":0,
"target":{
"_readyState":2,
"_error":{
"code":"JSON error"
},
"_result":null,
"_fileName":"file:///mnt/sdcard/com.app.id/update.sql",
"_realReader":{
"error":null,
"result":"",
"readyState":0
}
}
}
Please also note that 'com.app.id' is a place holder for the actual app ID - can't paste that for fear of sensitive names. I did try other folder names as well.
Other notable(?) items:
The download progress event seems to indicate that we are downloading precisely double the actual file size (wtf?)
Results are the same on android device and emulator
BlackBerry10 seems to work fine
Thanks in advance to any clever people....
OK.
This was the solution:
function gotFile (fileEntry) {
fileEntry.file (function (file) {
fileReader.readAsText(file);
});
};
So thanks a BAJILLION to this dude:
http://www.html5rocks.com/en/tutorials/file/filesystem/?ModPagespeed=noscript
In case you missed it, the magic is the call to the "file(...)" function on the fileEntry object.
Why it works on the BB10 WITHOUT it....aarrgggghhh

Categories

Resources