Use cordova plugin on ionic 3 app (cordova-androidwear) - ionic-framework

I have an ionic 3 app who shown markers on a map. But now I have a new request for the app to port it to wereable devices (Android wear and Apple watch). Show the markers in a map on the watch and some info...
After a lot of search and any questions on forums, I get a android wear plugin https://github.com/tgardner/cordova-androidwear but it is a cordova plugin.
The code in cordova is:
function watch(handle) {
var self = this;
AndroidWear.onDataReceived(handle, function(e) {
self.dataReceived(e.data);
});
self.handle = handle;
}
watch.prototype = {
dataReceived: function(data) {
app.logEvent("AndroidWear message received: " + data);
},
sendMessage: function(message) {
AndroidWear.sendData(this.handle, message);
app.logEvent("AndroidWear message sent!");
}
};
var app = {
watch: null,
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
var self = this;
document.addEventListener('deviceready', function() {
self.onDeviceReady();
}, false);
},
onDeviceReady: function() {
var self = this;
self.receivedEvent('deviceready');
if(AndroidWear) {
AndroidWear.onConnect(function(e) {
self.logEvent("AndroidWear connection established");
self.watch = new watch(e.handle);
});
}
var sendButton = document.getElementById("sendMessage");
sendButton.addEventListener("click", function() {
if(self.watch) {
self.watch.sendMessage("Mensaje");
}
});
},
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
this.logEvent('Received Event: ' + id);
},
logEvent: function(message) {
var events = document.getElementById("events");
var el = document.createElement("li");
el.innerHTML = message;
events.appendChild(el);
}
};
But I need to translate the cordova code to ionic code.
I try that:
(<any>window).AndroidWear.onConnect(() =>{
console.log("Androidwear : CONECTADO " );
})
(<any>window).AndroidWear.onDataReceived((data) =>{
console.log("Plugin: " + data);
})
But I received an execution error like this
[INFO:CONSOLE(13355)] "Didn't set nav root: TypeError: window.AndroidWear.onConnect(...) is not a function", source: file:///android_asset/www/build/main.js (13355)
I never translate the Cordova code into ionic 3, so maybe I've had stupid mistakes.
How can I translate that code to use the android-wear plugin on ionic 3 app?
Thanks you.

Related

SAPUI5 and NW Portal

I have an SAPUI5 application deployed on my portal.
I am trying get the user login logged on portal in my SAPUI5.
But when I run my application it is not get any data.
Bellow is my code
sap.ui.define([
'jquery.sap.global',
'sap/ui/core/Fragment',
'sap/ui/core/mvc/Controller',
'sap/ui/model/Filter',
'sap/ui/model/json/JSONModel'
], function(jQuery, Fragment, Controller, Filter, JSONModel) {
"use strict";
var CController = Controller.extend("sap.m.ZHRUI001.C", {
inputId: '',
valueHelpRequest: function(oController) {
this.inputId = oController.oSource.sId;
var sServiceUrl = "http://<my server host>:<my server port>/sap/bc/ui2/start_up";
var oModel = new sap.ui.model.odata.ODataModel(sServiceUrl, true, "user", "password");
var oJsonModel = new sap.ui.model.json.JSONModel();
oModel.read("/?", null, null, true, function(oData, response) {
oJsonModel.setData(oData);
});
sap.ui.getCore().setModel(oJsonModel);
// Handling of both confirm and cancel; clear the filter
var that = this;
var handleClose = function(oEvent) {
var oSelectedItem = oEvent.getParameter("selectedItem");
if (oSelectedItem) {
that.byId(that.inputId).setValue(oSelectedItem.getTitle());
}
oEvent.getSource().getBinding("items").filter([]);
};
// Create a SelectDialog and display it; bind to the same
// model as for the suggested items
if (!this._valueHelpSelectDialog) {
this._valueHelpSelectDialog = new sap.m.SelectDialog("valueHelpSelectDialog", {
title: "{fullName}",
items: {
template: new sap.m.StandardListItem({
title: "{fullName}",
active: true
})
},
search: function(oEvent) {
var sValue = oEvent.getParameter("value");
var oFilter = new sap.ui.model.Filter(
"name",
sap.ui.model.FilterOperator.Contains, sValue
);
oEvent.getSource().getBinding("items").filter([oFilter]);
},
confirm: handleClose,
cancel: handleClose
});
this._valueHelpSelectDialog.setModel(oJsonModel);
} else {
this._valueHelpSelectDialog.setModel(oJsonModel);
}
this._valueHelpSelectDialog.open();
}
});
return CController;
});
From what I'm reading you are speaking of a SAP Portal, I expect you have a 7.3+ version.
I have found the SAP doc you used to find the user, be careful because this is not the code for a SAPUI5 application running on a portal but for one running on a R/3 system, the endpoint /sap/bc/ui2/start_up doesn't exist on a NetWeaver portal.
What you could do is develop a simple REST service (by developping a Servlet) that will send back the user and all the details that you need.
These details can be found in the PortalComponentRequest which holds a IUser object, you can find a sample portal servlet on my Git here :
https://gitlab.com/Almiriad/sap-portal-samples
You simply have to send a GET request to the url
http[s]://youserver:your port/irj/servlet/prt/portal/prtroot/UserServletSample.UserInfoSampleServlet
and you'll get a JSo
{
"user": {
"user-name":"<LASTNAME>, <FIRSTNAME>",
"user-id":"<USER_ID>",
"user-email":"<USER#EMAIL.COM>"
}
}
I hope this will help you.
`
var oUserData;
var y = "/sap/bc/ui2/start_up";
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
oUserData = JSON.parse(xmlHttp.responseText);
}
};
xmlHttp.open("GET", y, false);
xmlHttp.send(null);
`
console oUserData to get login details of that user who logged in.

TypeError: Cannot read property 'AdMob' of undefined

I am using floatinghotpot plugin to show ads
cordova plugin add https://github.com/floatinghotpot/cordova-plugin-admob.git
This is my code for admob
$ionicPlatform.ready(function($location) {
var adMobId = {
admob_banner_key: 'ca-app-pub-3378914045953959/7363511027'
};
var options = {
interstitialAdId: 'ca-app-pub-3940256099942544/1033173712',
autoShow: true
};
var adMobPosition = {
BOTTOM_CENTER: 8
};
$scope.showBannerAd = function() {
try {
console.log('Show Banner Ad');
$cordovaAdMob.createBannerView({
adId: adMobId.admob_banner_key,
position: adMobPosition.BOTTOM_CENTER,
isTesting: true,
autoShow: true
});
} catch (e) {
alert(e);
}
}
$scope.showInterstitialAd = function(st) {
try {
console.log('Show Interstitial Ad');
$cordovaAdMob.createInterstitialView(options, function() {
admob.requestInterstitialAd({
'isTesting': true
},
function() {
admob.showAd(true);
},
function(error) {
console.log('failed to request ad ' + error);
}
);
},
function() {
console.log('failed to create Interstitial view');
});
} catch (e) {
alert("ALAS");
}
}
});
But when I call showBannerAd() using ng-init="showBannerAd()" it does not show ads and show this error message. How can I solve this problem? Am I missing anythinh important?
TypeError: Cannot read property 'AdMob' of undefined
This is the lists of installed plugins
com.google.admobsdk 6.12.2 "AdMob SDK for Android, iOS and WP8"
cordova-plugin-admob 2.10.0 "AdMob Plugin Pro"
cordova-plugin-console 1.0.2 "Console"
cordova-plugin-device 1.1.0 "Device"
cordova-plugin-extension 1.2.3 "Cordova Plugin Extension"
cordova-plugin-googleplayservices 19.0.3 "Google Play Services for Android"
cordova-plugin-inappbrowser 1.1.1 "InAppBrowser"
cordova-plugin-network-information 1.1.0 "Network Information"
cordova-plugin-splashscreen 3.0.0 "Splashscreen"
cordova-plugin-statusbar 2.0.0 "StatusBar"
cordova-plugin-whitelist 1.2.0 "Whitelist"
ionic-plugin-keyboard 1.0.8 "Keyboard"
I have created a JS File as below
var admobid = {};
// TODO: replace the following ad units with your own
if( /(android)/i.test(navigator.userAgent) ) {
//console.log("android");
admobid = { // for Android
banner: 'ca-app-pub-123123/123123',
interstitial: 'ca-app-pub-123123/123123'
};
} else if(/(ipod|iphone|ipad)/i.test(navigator.userAgent)) {
admobid = { // for iOS
banner: 'ca-app-pub-123123/123123',
interstitial: 'ca-app-pub-123123/4123123'
};
} else {
admobid = { // for Windows Phone
banner: 'ca-app-pub-123123/123123',
interstitial: 'ca-app-pub-123123/123123'
};
}
function initApp() {
if (! AdMob ) { alert( 'admob plugin not ready' ); return; }
// this will create a banner on startup
AdMob.createBanner( {
adId: admobid.banner,
position: AdMob.AD_POSITION.BOTTOM_CENTER,
isTesting: false, // TODO: remove this line when release
overlap: false,
offsetTopBar: false,
bgColor: 'black'
} );
// this will load a full screen ad on startup
AdMob.prepareInterstitial({
adId: admobid.interstitial,
isTesting: false, // TODO: remove this line when release
autoShow: false
});
}
if(( /(ipad|iphone|ipod|android|windows phone)/i.test(navigator.userAgent) )) {
document.addEventListener('deviceready', initApp, false);
} else {
initApp();
}
and included this js file into the index.html which is starter page of the application
Hope this may help you.
I have found with Apache Cordova that I have to put a setTimeout (aka sleep) and only execute my AdMob code after 1, 2 or 3 seconds.
Eg:
$ionicPlatform.ready(function($location) {
setTimeout(function()
{
var adMobId = {
admob_banner_key: 'ca-app-pub-3378914045953959/7363511027'
};
var options = {
interstitialAdId: 'ca-app-pub-3940256099942544/1033173712',
autoShow: true
};
...
...
...
etc...
}, 3000);
});

hash format error! using routing

I have developed an OpenUI5 app ant it works fine!
But every time that I invoke the routing I have this message:
2015-07-15 16:15:45 hash format error! The current Hash: /line/01 -
log
error
onHashChange
detectHashChange
jQuery.event.dispatch
jQuery.event.add.elemData.handle
It is not a blocking problem but it is annoying because it dirty and fills thi debug console..!
To call the router I write:
this.router = sap.ui.core.UIComponent.getRouterFor(this);
this.router.navTo("activities", {
"id_line": '01'
});
and this is the routing file:
routes: [
...
{
pattern: "line/{id_line}",
name: "activities",
target: ["master_search", "detail_activities"]
},
...
],
targets: {
master_search: {
viewName: "UniversalMenu",
viewLevel: 1,
controlAggregation: "masterPages"
}
,
detail_activities: {
viewName: "DetailActivity",
viewLevel: 4
}
...
}
Edit: this is a snippet where I use jQuery.sap.history
jQuery.sap.require("jquery.sap.history");
jQuery.sap.require("sap.m.InstanceManager");
sap.ui.controller("ui5bp.view.App", {
getDefaultPage : function () {
return "Menu";
},
onInit : function () {
var historyDefaultHandler = function (navType) {
if (navType === jQuery.sap.history.NavType.Back) {
//this.navBack(this.getDefaultPage());
} else {
this.navTo(this.getDefaultPage(), null, false);
}
};
var historyPageHandler = function (params, navType) {
if (!params || !params.id) {
jQuery.sap.log.error("invalid parameter: " + params);
} else {
if (navType === jQuery.sap.history.NavType.Back) {
this.navBack(params.id);
} else {
this.navTo(params.id, params.data, false);
}
}
};
jQuery.sap.history({
routes: [{
// This handler is executed when you navigate back to the history state on the path "page"
path : "page",
handler : jQuery.proxy(historyPageHandler, this)
}],
// The default handler is executed when you navigate back to the history state with an empty hash
defaultHandler: jQuery.proxy(historyDefaultHandler, this)
});
// subscribe to event bus
var bus = sap.ui.getCore().getEventBus();
bus.subscribe("nav", "to", this.navHandler, this);
bus.subscribe("nav", "back", this.navHandler, this);
bus.subscribe("nav", "virtual", this.navHandler, this);
},
navHandler: function (channelId, eventId, data) {
if (eventId === "to") {
this.navTo(data.id, data.data, true);
} else if (eventId === "back") {
//**************************************************
// if(data && data.id){
// this.navBack(data.id);
// } else {
// jQuery.sap.history.back();
// }
var app = this.getView().app;
if(data.type==="master"){
app.backMaster();
}else if(data.type==="detail"){
app.backDetail();
}else{alert("back to master o detail?");};
//**************************************************
} else if (eventId === "virtual") {
jQuery.sap.history.addVirtualHistory();
} else {
jQuery.sap.log.error("'nav' event cannot be processed. There's no handler registered for event with id: " + eventId);
}
},
navTo : function (id, data, writeHistory) {
if (id === undefined) {
// invalid parameter
jQuery.sap.log.error("navTo failed due to missing id");
} else {
var app = this.getView().app;
// navigate in the app control
app.to(id, "slide", data);
}
},
/*
navBack : function (id) {
if (!id) {
// invalid parameter
jQuery.sap.log.error("navBack - parameters id must be given");
} else {
// close open popovers
if (sap.m.InstanceManager.hasOpenPopover()) {
sap.m.InstanceManager.closeAllPopovers();
}
// close open dialogs
if (sap.m.InstanceManager.hasOpenDialog()) {
sap.m.InstanceManager.closeAllDialogs();
jQuery.sap.log.info("navBack - closed dialog(s)");
}
// ... and navigate back
var app = this.getView().app;
var currentId = (app.getCurrentPage()) ? app.getCurrentPage().getId() : null;
if (currentId !== id) {
app.backToPage(id);
jQuery.sap.log.info("navBack - back to page: " + id);
}
}
}
*/
});
In Component.js I had 2 rows where I set up custom myNavBack and myNavToWithoutHash functions:
// 3a. monkey patch the router
var oRouter = this.getRouter();
oRouter.myNavBack = ui5bp.MyRouter.myNavBack; //to comment
oRouter.myNavToWithoutHash = ui5bp.MyRouter.myNavToWithoutHash; //to comment
I have started from an example of app skeleton for my app and then I have implemented the routing with the logic suggested from the framework.
This coexistence of two different methods to navigate produced the error in console. Tahnkyou #TimGerlach
After the comment of the two rows errors have vanished.

how to handle onNotification event in ngCordova push plugin

as a code template doing it like this,
.controller('PushNotificationsCtrl', function ($scope, $cordovaPush) {
var androidConfig = {
"senderID":"372433177444",
"ecb":"onNotification"
};
$cordovaPush.register(androidConfig).then(function(result) {
// Success!
$scope.pushSuccess = result
}, function(err) {
$scope.pushSuccess = err;
});
I manage to successfully get an RegID from GCM. But then how do I manage onNotification from androidConfig ?
i found the solution.
instead of doing this :
var androidConfig = {
"senderID":"372433177444",
"ecb":"onNotification"
};
I do like this :
var androidConfig = {
"senderID":"372433177444",
"ecb":"window.onNotification"
};
then
window.onNotification = function(e) {
switch( e.event )
{
case 'registered':
if ( e.regid.length > 0 )
{
console.log("Your regID is : " + e.regid);
}
break;
case 'message':
// this is the actual push notification. its format depends on the data model from the push server
console.log('message = '+e.message);
angular.element(document.querySelector('#yata')).html(e.message);
break;
case 'error':
console.log('GCM error = '+e.msg);
break;
default:
console.log('An unknown GCM event has occurred');
break;
}
};
all work as expected now :)
Change the following code to ng-cordova.js:
//config.ecb = 'angular.element(' + injector + ').injector().get(\'$cordovaPush\').onNotification';
config.ecb = "angular.element(" + injector + ").injector().get('$cordovaPush').onNotification";
and then set the options configuration object as follows:
var options = {
android: {
senderID: "789175757493",
ecb:"onNotification",
forceShow: true
},
}
It will display notifications in notification drawer when application is opened.

Childbrowser plugin not working in Phonegap

I'm using Backbone, Require and Underscore Bundled with Phonegap or Cordova.
I tried using the childbrowser plugin but it wont work. I followed the instructions here.
http://blog.digitalbackcountry.com/2012/03/installing-the-childbrowser-plugin-for-ios-with-phonegapcordova-1-5/
define([
'jquery',
'backbone',
'underscore',
'base64',
'mobile',
'const',
'child',
'text!template/login/login.tpl.html'
],function($, Backbone, _, base64, Mobile, Const, ChildBrowser, template){
var EncodeAuth = function(user,pass)
{
var _tok = user + ':' + pass;
var _hash = Base64.encode(_tok);
return "Basic "+ _hash;
}
var LoginView = Backbone.View.extend({
events:{
"click .login-btn" : "Login",
"click .connection-btn" : "OpenSite"
},
initialize: function(){
},
Login: function(){
Const.USERNAME = $("#username").val();
Const.PASSWORD = $("#password").val();
if(!Const.USERNAME || !Const.PASSWORD)
{
navigator.notification.alert("Invalid Username/Password!");
$("input").val("");
}else{
var auth = EncodeAuth(Const.USERNAME,Const.PASSWORD);
var sendAuthorization = function (xhr) {
xhr.setRequestHeader('Authorization', auth)
};
this.model.save(this.model, {
beforeSend : sendAuthorization,
success: function(model,result){
if(result.ErrorMessage === null)
{
alert(JSON.stringify(result.Message));
$("input").val("");
}
else
{
alert(JSON.stringify(result.ErrorMessage));
$("input").val("");
}
},
error: function(model,result){
alert("Remote server returned an error. Not Found");
$("input").val("");
}
});
}
},
OpenSite: function(){
window.plugins.ChildBrowser.showWebPage("http://www.google.com");
}
});
return LoginView;
});
Any ideas?