My interest is relatively very basic. All I wanted an interstitial banner shows up in some pages of my hybrid application. I indeed appreciate your any comments and guidance since I am a novice developer, a hobbyist only.
I use Adobe PhoneGap build web interface and my "config.xml" is successful to build my apk which works charm.
<preference name="android-build-tool" value="gradle" />
<preference name="phonegap-version" value="cli-7.1.0" />
<plugin name="cordova-plugin-admob-free">
<variable name="ADMOB_APP_ID" value="ca-app-pub-1122334455667788~12345" />
</plugin>
My app is an HTML5 uses Jquery as well.
The index.html page calls following JS files.
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
There is no cordova.js as the phonegap injects during its build, My "js/index.js" file as follows,
var admobid = {}
if (/(android)/i.test(navigator.userAgent)) { // for android & amazon-fireos
admobid = {
banner: 'ca-app-pub-1122334455667788/12345',
interstitial: 'ca-app-pub-1122334455667788/12345',
}
} else if (/(ipod|iphone|ipad)/i.test(navigator.userAgent)) { // for ios
admobid = {
banner: 'ca-app-pub-1122334455667788/12345',
interstitial: 'ca-app-pub-1122334455667788/12345',
}
}
document.addEventListener('deviceready', function() {
admob.banner.config({
id: admobid.banner,
isTesting: true,
autoShow: true,
})
admob.banner.prepare()
admob.interstitial.config({
id: admobid.interstitial,
isTesting: true,
autoShow: true,
})
admob.interstitial.prepare()
document.getElementById('showAd').disabled = true
document.getElementById('showAd').onclick = function() {
admob.interstitial.show()
}
}, false)
document.addEventListener('admob.banner.events.LOAD_FAIL', function(event) {
console.log(event)
})
document.addEventListener('admob.interstitial.events.LOAD_FAIL', function(event) {
console.log(event)
})
document.addEventListener('admob.interstitial.events.LOAD', function(event) {
console.log(event)
document.getElementById('showAd').disabled = false
})
document.addEventListener('admob.interstitial.events.CLOSE', function(event) {
console.log(event)
admob.interstitial.prepare()
})
I build the app successfully but interstitial ads does not appear. (ps. banner does not appear either)
Could you please help me to figure this out? Huge thanks to all of you!
since you are trying to display your ad in testing mode remove
id: admobid.interstitial
and
id: admobid.banner
when you prepare the banner and interstital You need to show them like this :
admob.banner.show();
admob.interstitial.show();
Related
I am really new to the mobile development world and trying my hands on it using IonicFramework.
I am creating a login form and on successful login the user gets take to another state which is called viewMyList. Everything seems to be working fine when I run the command ionic serve I am able to login and proceed to the next state and all seems to be fine on iOS simulator as well but on Android simulator on clicking the login button nothing happens, I don't see any error either.
My attempt
login.html
<ion-view title="Login">
<ion-content class="has-header" padding="true">
<form class="list">
<h2 id="login-heading3" style="color:#000000;text-align:center;">Welcome back!</h2>
<div class="spacer" style="width: 300px; height: 32px;"></div>
<ion-list>
<label class="item item-input">
<span class="input-label">Email</span>
<input type="text" placeholder="" ng-model="credentials.username">
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="text" placeholder="" ng-model="credentials.password">
</label>
</ion-list>
<div class="spacer" style="width: 300px; height: 18px;"></div>
<a class="button button-positive button-block" ng-click="login()">Sign In</a>
</form>
</ion-content>
</ion-view>
ng-click is linked with login()
Here is my loginCtrl which contains the login() function
.controller('loginCtrl', function ($scope, $state, $ionicHistory, User) {
$scope.credentials = {
username: '',
password: ''
};
$scope.login = function () {
User.login($scope.credentials)
.then(function (response) {
console.log(JSON.stringify(response));
//Login should not keep any history
$ionicHistory.nextViewOptions({historyRoot: true});
$state.go('app.viewMyList');
})
};
$scope.message = "this is a message loginCtrl";
})
Here is my User service that takes care of the login logic
angular.module('app.user', [])
.factory('User', function ($http) {
var apiUrl = 'http://127.0.0.1:8000/api';
var loggedIn = false;
return {
login: function (credentials) {
console.log(JSON.stringify('inside login function'));
console.log(JSON.stringify(credentials));
return $http.post(apiUrl + '/tokens', credentials)
.success(function (response) {
console.log(JSON.stringify('inside .then of login function'));
var token = response.data.token;
console.log(JSON.stringify(token));
$http.defaults.headers.common.Authorization = 'Bearer ' + token;
persist(token);
})
.error(function (response) {
console.log('inside error of login function');
console.log(JSON.stringify(response));
})
;
},
isLoggedIn: function () {
if (localStorage.getItem("token") != null) {
return loggedIn = true;
}
}
};
function persist(token) {
window.localStorage['token'] = angular.toJson(token);
}
});
Here is the route behind the login
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'loginCtrl'
})
I am really clueless at the moment as I cant seem to figure out why nothing happens on Android, from my troubleshooting all I could find was when I click on login button the code does not seem to be going inside the following function.
$scope.login = function () {
User.login($scope.credentials)
.then(function (response) {
console.log(JSON.stringify(response));
//Login should not keep any history
$ionicHistory.nextViewOptions({historyRoot: true});
$state.go('app.viewMyList');
})
};
Any help will really be appreciated.
Install whitelist plugin first.
cordova plugin add cordova-plugin-whitelist
add following code in your config.xml file under your root directory of project
<allow-navigation href="http://example.com/*" />
or:
<allow-navigation href="http://*/*" />
If still you are facing any issue, then you can check console while you are running in android device using chrome remote debugging
Connect your device with your machine.(Make sure USB debugging should be enable on your mobile).
write chrome://inspect in browser in your desktop chrome.
you will see connected device, select inspect and check console for log.
I wanted to first say this is a really nice plugin (https://github.com/katzer/cordova-plugin-local-notifications) but having some difficulties getting it working.
I am using an Android and Phonegap CLI. I have tried both CLI 5.0 and now Phonegap 3.5.0, this is my config.xml:
<preference name="phonegap-version" value="3.5.0" />
In my config.xml I have tried all these combinations:
<plugin name="de.appplant.cordova.plugin.local-notification" spec="0.8.1" source="pgb" />
<gap:plugin name="de.appplant.cordova.plugin.local-notification" />
<plugin name="de.appplant.cordova.plugin.local-notification" source="pgb" />
However the notifications do not appear - nothing happens on the phone - nothing, nada, zilch. I have also downloaded the KitchenSink App (https://github.com/katzer/cordova-plugin-local-notifications/tree/example) and installed on Phonegap build and my phone and nothing again happens..
This is my code on index.html so when the phone fires it should register a local notification asap:
cordova.plugins.notification.local.registerPermission(function (granted) {
// console.log('Permission has been granted: ' + granted);
});
cordova.plugins.notification.local.schedule({
id: 1,
title: 'Reminder',
text: 'Dont forget to pray today.',
every: 'minute',
icon: 'res://icon',
smallIcon: 'res://ic_popup_sync'
});
I also tried
cordova.plugins.notification.local.schedule({
id: 2,
text: "Good morning!",
firstAt: tomorrow_at_8_am,
every: "day" // "minute", "hour", "week", "month", "year"
});
Even the KitchenSink app is not working - nothing happens on the phone??
My Android version is: 5.1.1
How can I get local notifications to appear in Phonegap?
I too have spent many hours trying to get this plugin working & I have, but i do find it to be one of the most temperamental.
Within your js -
var testNotifications = function () {
document.addEventListener("deviceready", function () {
console.warn("testNotifications Started");
// Checks for permission
cordova.plugin.notification.local.hasPermission(function (granted) {
console.warn("Testing permission");
if( granted == false ) {
console.warn("No permission");
// If app doesnt have permission request it
cordova.plugin.notification.local.registerPermission(function (granted) {
console.warn("Ask for permission");
if( granted == true ) {
console.warn("Permission accepted");
// If app is given permission try again
testNotifications();
} else {
alert("We need permission to show you notifications");
}
});
} else {
var pathArray = window.location.pathname.split( "/www/" ),
secondLevelLocation = window.location.protocol +"//"+ pathArray[0],
now = new Date();
console.warn("sending notification");
var isAndroid = false;
if ( device.platform === "Android" ) {
isAndroid = true;
}
cordova.plugin.notification.local.schedule({
id: 9,
title: "Test notification 9",
text: "This is a test notification",
sound: isAndroid ? "file://sounds/notification.mp3" : "file://sounds/notification.caf",
at: new Date( new Date().getTime() + 10 )
// data: { secret:key }
});
}
});
}, false);
};
Now on your html tag -
<button onclick="testNotifications()">Test notification</button>
That should trigger a notification or warn you that it needs permissions
Also top tip is to make sure your notifications are in a folder in the root of the project. android should be mp3 and ios caf
Answer 1 :for version 3.5.0
have a look at plugin's plugin.xml. see line 22
<engine name="cordova" version=">=3.6.0" />
that means plugin only supports version greater than 3.6.0 and you are using 3.5.0
Answer 2 :for version 5.0 or higher
Try the following code as index.html. if it runs perfectly then and other options in to notification.schedule.
as we haven't provided time(at) option notification will triggered immediately.
<html>
<script type="text/javascript" src="cordova.js"></script>
<script>
document.addEventListener('deviceready', onDeviceReady.bind(this), false);
function onDeviceReady() {
cordova.plugins.notification.local.schedule({
id: 1,
title: "Sample Notification",
text: "foo",
every: "week",
data: { meetingId: "123#fg8" }
});
};
</script>
<body>
</body>
</html>
i have created a simple app in Phonegap build ,and integrated and linked the app with Google admob ,when i test the app in test ads mode it showing the test ads ,but as i published the app on google play it doesn't showing original ads .
My Code For Preparing ads
var admobid = {};
if( /(android)/i.test(navigator.userAgent) ) {
admobid = { // for Android
banner: 'ca-app-pub-5584769932279177/2482584044',
interstitial: 'ca-app-pub-5584769932279177/1005850846'
};
} else if(/(ipod|iphone|ipad)/i.test(navigator.userAgent)) {
admobid = { // for iOS
banner: '',
interstitial: ''
};
} else {
admobid = { // for Windows Phone
banner: '',
interstitial: ''
};
}
function initApp() {
if (AdMob) {
AdMob.setOptions({
bgColor: 'black', // color name, or '#RRGGBB'
});
AdMob.createBanner({
adId : admobid.banner,
position : AdMob.AD_POSITION.BOTTOM_CENTER,
autoShow : true
});
}
if(AdMob){
AdMob.prepareInterstitial({
adId:admobid.interstitial,
autoShow:false
}
);
}
}
if(( /(ipad|iphone|ipod|android|windows phone)/i.test(navigator.userAgent) )) {
document.addEventListener('deviceready', initApp, false);
} else {
initApp();
}
Code for Showing Interstitial Ads
window.onload=function(){
window.onbeforeunload = function(){
if(AdMob)
AdMob.showInterstitial();
};
}
And also included the following lines in my config file
<preference name="android-build-tool" value="gradle" />
<gap:plugin name="cordova-plugin-admobpro" source="npm" />
To wait check and approve (up to 2 days).
Generally this happens because no ads is available in that region where you are testing, if it is displaying test ads it will show the ads if available.
your Code is correct if it is showing the Test ads or the ads are taking time to load
i download the sample cordova admob project from github. i extracted and tested in android studio and debug on a galaxy s4. when the app opens it brings an alert"admob plugin not loaded". I've install the admob plugin, together with the internet plugin in my project
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
<title>Hello World</title>
<script type="text/javascript" src="cordova.js"></script>
<style type="text/css">
html, body { width:100%; height:100%; margin:0; padding:0; overflow:hidden; background-color:white; }
div#fullpage { width:100%; height:100%; margin:0; padding:0; border:0px solid red; text-align:center; vertical-align:middle; }
button { font-size: 22px; }
</style>
</head>
<body onload="onDocLoad()" onresize="onResize()">
<script>
function onDocLoad() {
if(( /(ipad|iphone|ipod|android|windows phone)/i.test(navigator.userAgent) )) {
document.addEventListener('deviceready', initApp, false);
} else {
initApp();
}
}
function initApp() {
initAd();
// display the banner at startup
window.plugins.AdMob.createBannerView();
}
function initAd(){
if ( window.plugins && window.plugins.AdMob ) {
var ad_units = {
ios : {
banner: 'ca-app-pub-6869992474017983/4806197152',
interstitial: 'ca-app-pub-6869992474017983/7563979554'
},
android : {
banner: 'ca-app-pub-6869992474017983/9375997553',
interstitial: 'ca-app-pub-6869992474017983/1657046752'
},
wp8 : {
banner: 'ca-app-pub-6869992474017983/8878394753',
interstitial: 'ca-app-pub-6869992474017983/1355127956'
}
};
var admobid = "";
if( /(android)/i.test(navigator.userAgent) ) {
admobid = ad_units.android;
} else if(/(iphone|ipad)/i.test(navigator.userAgent)) {
admobid = ad_units.ios;
} else {
admobid = ad_units.wp8;
}
window.plugins.AdMob.setOptions( {
publisherId: admobid.banner,
interstitialAdId: admobid.interstitial,
bannerAtTop: false, // set to true, to put banner at top
overlap: false, // set to true, to allow banner overlap webview
offsetTopBar: false, // set to true to avoid ios7 status bar overlap
isTesting: false, // receiving test ad
autoShow: true // auto show interstitial ad when loaded
});
registerAdEvents();
} else {
alert( 'admob plugin not ready' );
}
}
// optional, in case respond to events
function registerAdEvents() {
document.addEventListener('onReceiveAd', function(){});
document.addEventListener('onFailedToReceiveAd', function(data){});
document.addEventListener('onPresentAd', function(){});
document.addEventListener('onDismissAd', function(){ });
document.addEventListener('onLeaveToAd', function(){ });
document.addEventListener('onReceiveInterstitialAd', function(){ });
document.addEventListener('onPresentInterstitialAd', function(){ });
document.addEventListener('onDismissInterstitialAd', function(){ });
}
function onResize() {
var msg = 'web view: ' + window.innerWidth + ' x ' + window.innerHeight;
document.getElementById('sizeinfo').innerHTML = msg;
}
</script>
<div id="fullpage">
<p>Demo for AdMob Plugin</p>
<p><button onclick="window.plugins.AdMob.createBannerView();">create Ad</button> <button onclick="window.plugins.AdMob.destroyBannerView();">remove Ad</button></p>
<p><button onclick="window.plugins.AdMob.showAd(true,function(){},function(e){alert(JSON.stringify(e));});">show Ad</button> <button onclick="window.plugins.AdMob.showAd(false);">hide Ad</button></p>
<p><button onclick="window.plugins.AdMob.createInterstitialView();">create Interstitial Ad</button></p>
<p><button onclick="window.plugins.AdMob.showInterstitialAd(true,function(){},function(e){alert(JSON.stringify(e));});">show Interstitial Ad</button></p>
<div id="sizeinfo">width * height</div>
<div>Try rotate screen to test the orientation change</div>
</div>
</body>
</html>
Since you don't specify the actual admob plugin you use, I can answer using another plugin (https://github.com/sunnycupertino/cordova-plugin-admob-simple) that does what you need:
to add the plugin
cordova plugin add cordova-plugin-admob-simple
Integration is as follows:
-Add the following javascript functions, put in your own ad code, play with the variables if you want.
-Call initAd() from onDeviceReady(), and showBannerFunc() and showInterstitialFunc() to show ads.
//initialize the goodies
function initAd(){
if ( window.plugins && window.plugins.AdMob ) {
var ad_units = {
ios : {
banner: 'ca-app-pub-xxxxxxxxxxx/xxxxxxxxxxx', //PUT ADMOB ADCODE HERE
interstitial: 'ca-app-pub-xxxxxxxxxxx/xxxxxxxxxxx' //PUT ADMOB ADCODE HERE
},
android : {
banner: 'ca-app-pub-xxxxxxxxxxx/xxxxxxxxxxx', //PUT ADMOB ADCODE HERE
interstitial: 'ca-app-pub-xxxxxxxxxxx/xxxxxxxxxxx' //PUT ADMOB ADCODE HERE
}
};
var admobid = ( /(android)/i.test(navigator.userAgent) ) ? ad_units.android : ad_units.ios;
window.plugins.AdMob.setOptions( {
publisherId: admobid.banner,
interstitialAdId: admobid.interstitial,
adSize: window.plugins.AdMob.AD_SIZE.SMART_BANNER, //use SMART_BANNER, BANNER, IAB_MRECT, IAB_BANNER, IAB_LEADERBOARD
bannerAtTop: false, // set to true, to put banner at top
overlap: true, // banner will overlap webview
offsetTopBar: false, // set to true to avoid ios7 status bar overlap
isTesting: false, // receiving test ad
autoShow: false // auto show interstitial ad when loaded
});
registerAdEvents();
window.plugins.AdMob.createInterstitialView(); //get the interstitials ready to be shown
window.plugins.AdMob.requestInterstitialAd();
} else {
//alert( 'admob plugin not ready' );
}
}
//functions to allow you to know when ads are shown, etc.
function registerAdEvents() {
document.addEventListener('onReceiveAd', function(){});
document.addEventListener('onFailedToReceiveAd', function(data){});
document.addEventListener('onPresentAd', function(){});
document.addEventListener('onDismissAd', function(){ });
document.addEventListener('onLeaveToAd', function(){ });
document.addEventListener('onReceiveInterstitialAd', function(){ });
document.addEventListener('onPresentInterstitialAd', function(){ });
document.addEventListener('onDismissInterstitialAd', function(){
window.plugins.AdMob.createInterstitialView(); //REMOVE THESE 2 LINES IF USING AUTOSHOW
window.plugins.AdMob.requestInterstitialAd(); //get the next one ready only after the current one is closed
});
}
//display the banner
function showBannerFunc(){
window.plugins.AdMob.createBannerView();
}
//display the interstitial
function showInterstitialFunc(){
window.plugins.AdMob.showInterstitialAd();
}
I am having trouble receiving any type of callback for the push notifications plugin for phonegap build, I have included the plugin inside config.xml.
I have signed up to GCM and got my project number needed for pushNotification.register().
I also have access to the window.plugins.pushNotification object so I know it's included the plugin.
PhoneGap Build Version: 3.1
Hydration: Disabled
Debug: Enabled
Device: Samsung Tab 2
My index.html js files included are:
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="PushNotification.js"></script>
<script type="text/javascript" src="js/lib/jquery.js" ></script>
<script type="text/javascript" src="js/lib/handlebars.js"></script>
<script type="text/javascript" src="js/handlebars/helpers.js"></script>
<script type="text/javascript" src="js/plugins/fastclick.js"></script>
<script type="text/javascript" src="js/app.js"></script>
My config.xml plugins included are:
// plugins
<gap:plugin name="org.apache.cordova.console" />
<gap:plugin name="org.apache.cordova.device" />
<gap:plugin name="org.apache.cordova.geolocation" />
<gap:plugin name="org.apache.cordova.dialogs" />
<gap:plugin name="org.apache.cordova.inappbrowser" />
<gap:plugin name="org.apache.cordova.splashscreen" />
<gap:plugin name="com.phonegap.plugins.pushplugin" />
// access to external domains
<access origin="*"/>
My app.js call to pushNotification.register()
var app = {
init: function() {
document.addEventListener("deviceready", this.onDeviceReady, false);
},
onDeviceReady: function(){
// DO STUFF
// ....
// ENABLE PUSH
this.push_init();
},
push_init: function(){
app.SENDER_ID = 123456789; // replaced by my actual GCM project no
var pushNotification = window.plugins.pushNotification;
pushNotification.register(
function(){alert('Push: win');}, // never called
function(){alert('Push: Error');}, // never called
{ senderID: app.SENDER_ID, ecb: "app.push_android" }
);
},
// never called
push_android: function(e){
alert('connection established...');
console.log( 'successfully started android' );
console.log( e );
}
};
// start the app
app.init();
After that is called nothing is executed, app.push_android() is a function of app object.
If i don't enter a senderID I get an error saying no sender ID so I know that something is working. This is so frustrating any ideas?
PS - I also noticed something weird, when I console.log the window.plugins.pushNotification it returns an empty object, however I can still call window.plugins.pushNotification.register(), but I thought I would be visible inside the console.log.
I think I've found the solution.
I was passing an integer instead of a string for the property senderID in the object
Doesnt work
pushNotification.register(
function(){alert('Push: win');}, // NOT called
function(){alert('Push: Error');}, // NOT called
{ senderID: 123456789, ecb: "app.push_android" }
);
DOES work
pushNotification.register(
function(){alert('Push: win');}, // called
function(){alert('Push: Error');}, // called
{ senderID: "123456789", ecb: "app.push_android" }
);
Try this push notification code -
var pushNotification;
document.addEventListener('deviceready', onDeviceReady, true);
function onDeviceReady() {
try {
pushNotification = window.plugins.pushNotification;
if (device.platform == 'android' || device.platform == 'Android') {
pushNotification.register(successHandler, errorHandler, { "senderID": "123456789", "ecb": "onNotificationGCM" }); // required!
}
else {
pushNotification.register(tokenHandler, errorHandler, { "badge": "true", "sound": "true", "alert": "true", "ecb": "onNotificationAPN" }); // required!
}
}
catch (err) {
txt = "There was an error on this page.\n\n";
txt += "Error description: " + err.message + "\n\n";
alert(txt);
}
};
// handle GCM notifications for Android
function onNotificationGCM(e) {
switch (e.event) {
case 'registered':
if (e.regid.length > 0) {
alert(e.regid);
storeToken(e.regid);
}
break;
case 'message':
if (e.foreground) {
var my_media = new Media("beep.wav");
my_media.play();
}
else {
// otherwise we were launched because the user touched a notification in the notification tray.
}
break;
case 'error':
break;
default:
break;
}
}
Refer Link
Refer Devgirl's Weblog