Ads not displaying with Admob PhoneGap Plugin - android

I have an Android application build with PhoneGap 3.4.
The plugin I am running is: https://github.com/floatinghotpot/cordova-plugin-admob.git
The installation instructions are:
A simplified method (tested on Cordova 3.4.0)
1. Install the Google Play Services plugin:
```cordova plugin add https://github.com/MobileChromeApps/google-play-services.git```
2. Install _this_ plugin:
```cordova plugin add https://github.com/floatinghotpot/cordova-plugin-admob.git```
The directions for displaying the Ads are:
##Using the Plugin:
There are 3 calls needed to get AdMob Ads:
1. `createBannerView`
Takes in a object containing a publisherId and adSize, as well as success
and failure callbacks. An example call is provided below:
window.plugins.AdMob.createBannerView(
{
'publisherId': 'INSERT_YOUR_PUBLISHER_ID_HERE',
'adSize': window.plugins.AdMob.AD_SIZE.BANNER
},
successCallback,
failureCallback
);
2. `requestAd`
Takes in an object containing an optional testing flag, and an optional
list of extras. This method should only be invoked once createBannerView
has invoked successCallback. An example call is provided below:
window.plugins.AdMob.requestAd(
{
'isTesting': false,
'extras': {
'color_bg': 'AAAAFF',
'color_bg_top': 'FFFFFF',
'color_border': 'FFFFFF',
'color_link': '000080',
'color_text': '808080',
'color_url': '008000'
},
},
successCallback,
failureCallback
);
3. `showAd`
Show or hide the Ad.
This method should only be invoked once createBannerView has invoked successCallback.
An example call is provided below:
window.plugins.AdMob.showAd(
true,
successCallback,
failureCallback
);
And here is my attempt:
function onLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
if(window.plugins && window.plugins.AdMob) {
var admob_android_key = 'ca-app-pub-xxxxxxxxxxxxxxxxxxxxxxx';
var adId = (navigator.userAgent.indexOf('Android') >=0) ? admob_android_key : admob_ios_key;
var am = window.plugins.Admob;
am.createBannerView(
{
'publisherId': adId,
'adSize': am.AD_SIZE.BANNER,
'bannerAtTop': false
},
function() {
am.requestAd(
{ 'isTesting':false },
function(){
am.showAd( true );
},
function(){ alert('failed to request ad'); }
);
},
function(){ alert('failed to create banner view'); }
);
} else {
alert('AdMob plugin not available/ready.');
}
}
Any idea where I am going wrong with this? Thank you in advance.

what you pasted is too complex
there are several to show ad right.
1.install ,just add this in your phonegap build config
<gap:plugin name="com.admob.plugin" version="1.0.0" source="plugins.cordova.io"/>
2.config admob
admob.showBannerAbsolute(admob.BannerSize.BANNER,0,70);
3.show admob ad when you want.
admob.showBanner(admob.BannerSize.BANNER,admob.Position.TOP_APP);
that is all.

Related

Cordova pickcontact doesn't work

I try to pick a contact with cordova plugin contacts, but I still have a bug. My button #pickContact opens correctly the activity where I can tap on a contact. But when I tap on one, nothing happens. When I go back to my page, I have the error message OPERATION_CANCELLED_ERROR (code 6).
I really don't understand where is the problem. I run my app on Android Marshmallow. I thought about a permission problem, but my app can find correctly contacts with navigator.contacts.find, but not with navigator.contacts.pickContact
Here is my code :
function pickContact() {
navigator.contacts.pickContact(function(contact){
alert('ok !');
},function(err){
alert('bug !' + err);
console.log('Error: ' + err);
});
}
var app = {
// Application Constructor
initialize: function() {
this.onDeviceReady();
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
document.addEventListener("deviceready", this.onDeviceReady, false);
} else {
this.onDeviceReady();
}
},
onDeviceReady: function() {
$("#pickContact").click(pickContact);
},
// Update DOM on a Received Event
receivedEvent: function(id) {
}
};
app.initialize();
Thanks for your help !
As per the reference doc of contacts plugin your selected contact will set into JSON.stringify(contact) you can alert it to see which contacts are selected (I have used this plugin but I don't need this function to pick any single contact so not sure if there is any done button or not) then press done or ok button, which will redirect you to your another function where you can get that contacts or fulfill your next requirements.
function pickContact() {
navigator.contacts.pickContact(function(contact){
alert(JSON.stringify(contact));
//This is added by me, on done button click or single selection
setContacts(contact);
},function(err){
alert('bug !' + err);
console.log('Error: ' + err);
});
}
//This is added by me
function setContacts(ct)
{
alert(JSON.stringify(ct));
$("#contactlist").append(ct);
//or
var getData = JSON.parse(ct);
if(getData.length > 1)
{
for(i=0;i<getData.length;i++)
{
$("#contactlist").append(getData[i]);
}
}
}
Let me know if I am wrong or right.
Thanks a lot for your answer. Unfortunately , your code doesn't works for me, but I found what to do :
When pickcontact opens your native app "contacts", your cordova app is removed on background. On android, that means that you loose the state of your app, and so you have a bug. To solve the problem, you need to add onresume event on your js file, like this :
var app = {
// Application Constructor
initialize: function() {
this.onDeviceReady();
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
document.addEventListener("deviceready", this.onDeviceReady, false);
} else {
this.onDeviceReady();
}
},
onDeviceReady: function() {
$("#pickContact").click(pickContact);
},
onResume: function(resumeEvent) {
//alert('onResume');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
}
};
app.initialize();
After that, you can retrieve your picked contact with a function like this :
function pickContact() {
navigator.contacts.pickContact(function(contact){
$("#divTest").append('<p>The following contact has been selected:' + JSON.stringify(contact));
},function(err){
alert('bug !' + err);
console.log('Error: ' + err);
});
}
So, like everytime in programming, when you know the answer, that's easy. But when you don't know, you loose hours and hours...
I hope that will help someone.

Right way of placing interestitial ad in ionic android platform

For showing interestitial ad in my android app (which i have made using ionic) i have used the following code :
<script type="text/javascript">
function runads(){
document.addEventListener("deviceready", onDeviceReady, false);
}
function initAds() {
if (admob) {
var adPublisherIds = {
ios : {
banner : "###############",
interstitial : "##################"
},
android : {
banner : "#############",
interstitial : "#########################"
}
};
var admobid = (/(android)/i.test(navigator.userAgent)) ? adPublisherIds.android : adPublisherIds.ios;
admob.setOptions({
publisherId: admobid.banner,
interstitialAdId: admobid.interstitial,
tappxIdiOs: "/XXXXXXXXX/Pub-XXXX-iOS-IIII",
tappxIdAndroid: "/XXXXXXXXX/Pub-XXXX-Android-AAAA",
tappxShare: 0.5
});
registerAdEvents();
} else {
alert('AdMobAds plugin not ready');
}
}
function onAdLoaded(e) {
if (e.adType === admob.AD_TYPE.INTERSTITIAL) {
admob.showInterstitialAd();
showNextInterstitial = setTimeout(function() {
admob.requestInterstitialAd();
}, 2 * 60 * 1000); // 2 minutes
}
}
// optional, in case respond to events
function registerAdEvents() {
document.addEventListener(admob.events.onAdLoaded, onAdLoaded);
document.addEventListener(admob.events.onAdFailedToLoad, function (e) {});
document.addEventListener(admob.events.onAdOpened, function (e) {});
document.addEventListener(admob.events.onAdClosed, function (e) {});
document.addEventListener(admob.events.onAdLeftApplication, function (e) {});
document.addEventListener(admob.events.onInAppPurchaseRequested, function (e) {});
}
function onDeviceReady() {
document.removeEventListener('deviceready', onDeviceReady, false);
initAds();
// display a banner at startup
admob.createBannerView();
// request an interstitial
admob.requestInterstitialAd();
}
My interestitial ad is showing perfectly using this code.Then, i have uploaded it in google play store.suddenly i have got a message from google Admob team regarding interestitial ad placing . The message is -
Hello,We are alerting you that your app is currently in violation of the AdMob program policies. Importantly, this will require action on your part to ensure no disruption in ad serving. Please read below for more information on the actions you need to take:
Violation explanation
LAYOUT ENCOURAGES ACCIDENTAL CLICKS - INTERSTITIAL ADS:Publishers are not permitted to encourage users to click AdMob interstitial ads in any way. Please review how you’ve implemented interstitial ads and be mindful of the following non-compliant implementation(s):Interstitial ads that load unexpectedly while a user is viewing the app’s content.For more information about our policies and tips for how to comply please read the following:
Interstitial ads that load unexpectedly while a user is viewing the app’s content.For more information about our policies and tips for how to comply please read the following:AdMob ad placement policyAdMob interstitial ad guidanceAdMob preload instructions for Android and iOSAction required: Please make changes immediately to your app to comply with AdMob program policies.Current account status: ActiveYou do not need to contact us once you've made the necessary changes to your app. Please be aware that if additional violations are accrued, ad serving may be disabled to the app listed above.Note that the app listed above is just one example and the same violation may exist on other apps you own. We suggest that you review all your apps for compliance with the AdMob program policies to reduce the likelihood of future warnings.For more information regarding our policy warning notifications, visit our Help Center.Thank you for your cooperation.Sincerely,The Google AdMob Team
How Can i solve this problem ?
Probably what is going on is that the loading of an interstitial ad takes some time, so you need to plan the loading of an interstitial and ensure the interstitial is available when you need to show it. If not, launching admob.showInterstitialAd() will load the interstital and show it when it is available (as the flag autoShowInterstitial is true by default, see https://github.com/appfeel/admob-google-cordova/wiki/setOptions).
There is a complete example on how to plan the interstitials: https://github.com/appfeel/admob-google-cordova/wiki/showInterstitialAd.
Basically what you do is to request an interstitial and let the app know if the interstitial is available or not. Probably your code for ionic should look like this:
angular.module('myApp', ['admobModule'])
.constant('AdmobConfig', {
bannerId: /(android)/i.test(navigator.userAgent) ? "ca-app-pub-XXXXXXXXXXXXXXXX/ANDROID_BANNER_ID" : "ca-app-pub-XXXXXXXXXXXXXXXX/IOS_BANNER_ID",
interstitialId: /(android)/i.test(navigator.userAgent) ? "ca-app-pub-XXXXXXXXXXXXXXXX/ANDROID_INTERSTITIAL_ID" : "ca-app-pub-XXXXXXXXXXXXXXXX/IOS_INTERSTITIAL_ID",
})
.config(function (admobSvcProvider, AdmobConfig) {
admobSvcProvider.setOptions({
publisherId: AdmobConfig.bannerId,
interstitialAdId: AdmobConfig.interstitialId,
autoShowInterstitial: false,
});
})
.run(function ($rootScope, $ionicPlatform, $timeout, admobSvc) {
admobSvc.requestInterstitialAd();
$rootScope.isInterstitialAvailable = false;
$rootScope.isAppForeground = false;
$rootScope.$on(admobSvc.events.onAdLoaded, function onAdLoaded(evt, e) {
if ($rootScope.isAppForeground) {
if (e.adType === admobSvc.AD_TYPE.INTERSTITIAL) {
$rootScope.isInterstitialAvailable = true;
}
}
});
$rootScope.$on(admobSvc.events.onAdOpened, function onAdOpened(evt, e) {
if ($rootScope.isAppForeground) {
if (e.adType === admobSvc.AD_TYPE.INTERSTITIAL) {
$rootScope.isInterstitialAvailable = false;
$timeout(admobSvc.requestInterstitialAd, 1); // Immediately request next interstitial asap
}
}
});
$ionicPlatform.on('pause', function onPause() {
if ($rootScope.isAppForeground) {
$rootScope.isAppForeground = false;
}
});
$ionicPlatform.on('resume', function onResume() {
if (!$rootScope.isAppForeground) {
$timeout(admobSvc.requestInterstitialAd, 1);
$rootScope.isAppForeground = true;
}
});
})
.controller('YourController', function ($rootScope, admobSvc) {
var vm = this;
vm.pleaseShowInterstitial = function () {
if ($rootScope.isInterstitialAvailable) {
admobSvc.showInterstitialAd();
}
};
});
Also note that there is a management for foreground app. This is important as if not, the user could put the app in background and the interstitial would automatically be shown. In your case it is not so relevant, as you control when the interstitial is shown, but I recommend you to keep this, in case you decide to start auto showing interstitials :)

ngCordova barcode scanner is providing Object Object in the scannedData

I am new to Cordova. I am trying to scan a QR code by referring to this document. When I do that in alert, it is providing [object Object] in scanned data. Anyone have idea on this.
document.addEventListener("deviceready", function () {
$cordovaBarcodeScanner
.scan()
.then(function(barcodeData) {
console.log(barcodeData);
alert(barcodeData);
}, function(error) {
console.log(error);
});
$cordovaBarcodeScanner
.encode(BarcodeScanner.Encode.TEXT_TYPE, "http://www.nytimes.com")
.then(function(success) {
alert(success);
}, function(error) {
// An error occurred
});
},false);
Can anyone tell me what is the use of encode here?
When you you get a scanned bar code (or qr code) data in .then block, you get an object (hash) of data. If you want to see it in the alert box then you have to stringify it:
alert(JSON.stringify(barcodeData));
Since $cordovaBarcodeScanner plugin works only on physical devise, you don't want to use console.log.
Regarding .encode method. It is currently not supported. So, there is no point of using it. The documentation also mentions this fact. So, just remove that part of your code:
document.addEventListener("deviceready", function () {
$cordovaBarcodeScanner
.scan()
.then(function(barcodeData) {
alert(JSON.stringify(barcodeData));
}, function(error) {
alert(JSON.stringify(error));
});
}, false);

ionic + cordova plugin and background mode

I'm making an app with ionic for car drivers. The app takes coordinates every one minute and write them on remote server, this helps me to tracking route and show cars on Google map.
I use Cordova plugin and it works fine except when screen turns off or the app goes into the background. I installed katzer cordova-plugin-background-mode, when the app go into background I see the message : app is now in background, the plugin informs me but nothing else, the app stopped! .
No data sent to remote server, when I resume the app all is back to normal, I use Android platform. How can i solve?
app.js code
angular.module('starter', ['ionic', 'ngCordova','LocalStorageModule', 'starter.controllers', 'starter.services'])
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleLightContent();
}
cordova.plugins.backgroundMode.enable();
});
})
.....
controllers.js
angular.module('starter.controllers', [])
.controller('GeoCtrl', function($scope, $cordovaGeolocation, $cordovaNetwork, $http, $interval) {
var reloadCoordinates = function() {
var watchOptions = {
timeout : 10000,
enableHighAccuracy: false // may cause errors if true
};
var watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function(err) {
// error
},
function(position) {
//Latitudine e Longitudine
var lat = position.coords.latitude
var lon = position.coords.longitude
$scope.latitude = lat
$scope.longitude = lon
$http.post('http://192.168.1.2/get-data.php', { "lat": lat, "lon" : lon }).then(function(resp) {
console.log('Success Lat:'+resp.data.lat+' Lon:'+resp.data.lon);
watch.clearWatch();
}, function(err) {
console.error('ERR', err);
// err.status will contain the status code
})
});
};//end reloadCoordinates
$interval(reloadCoordinates, 60000);
reloadCoordinates();
})
I know this is an old thread, but I did manage to get this working, with:
cordova.plugins.backgroundMode.on('enable', function(){
//your code here, will execute when background tasks is enabled
loop();
});
function loop(){
console.log("loop");
$timeout(loop, 1000);
}
cordova.plugins.backgroundMode.enable();
#Cristian,
after enabling plugin, you should call your function or write your logic in this function.
cordova.plugins.backgroundMode.onactivate = function() {
// your logic here
// or call any other service, factory function
};
Are you trying to make an app that does something every x minutes, even when the app is in the background and/or the screen is turned off.... tried backgound-mode plugin but it only works reliably when the phone is plugged in... did you ever found a solution to this?
Install the plugin using the cordova command line utility:
$ cordova plugin add https://github.com/boltex/cordova-plugin-powermanagement.git
here's how i use it along with the background mode plugin so the app is never in background and always running as a service...:
if( ionic.Platform.isAndroid() ){
cordova.plugins.backgroundMode.enable();
window.powerManagement.dim(function() {
console.log('Wakelock acquired');
}, function() {
console.log('Failed to acquire wakelock');
});
window.powerManagement.setReleaseOnPause(false, function() {
console.log('setReleaseOnPause successfully');
}, function() {
console.log('Failed to set');
});
}
Final Step Deactivate your plugin when you finished your service as
cordova.plugins.backgroundMode.disable()

Cordova InAppBrowser Loading Spinner for Android

I've an app built with cordova and InAppBrowser. I'm trying to show a "loading spinner" in every page.
In iOS it's working well on every page I load, but Android fails.
On iOS I just edited self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] this line in CDVInappBrowser.m and works.
Does Android have a similar feature ?
Here is my code:
// Cordova is ready
function onDeviceReady() {
var ref = window.open("http://m.estadao.com.br/?load-all=true", "_blank", "location=no", "toolbar=no", "closebuttoncaption=a", "EnableViewPortScale=no");
navigator.notification.activityStart("Loading", "Loading...");
setTimeout(function(){
navigator.notification.activityStop();
}, 5000);
}
Check this plugin:
https://github.com/Paldom/SpinnerDialog
Working for me in Android. You should use this method to show a spinner with title and message:
window.plugins.spinnerDialog.show("Loading","Loading...");
Your code would be:
function onDeviceReady() {
var ref = window.open("http://m.estadao.com.br/?load-all=true", "_blank", "location=no", "toolbar=no", "closebuttoncaption=a", "EnableViewPortScale=no");
window.plugins.spinnerDialog.show("Loading","Loading...");
setTimeout(function(){
window.plugins.spinnerDialog.hide();
}, 5000);
}
Resvolvi dessa forma
//window.open Example
// Wait for device API libraries to load
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// external url
// var ref = window.open(encodeURI('http://mfsom.com.br/'), '_blank', 'location=no','toolbar=no');
//relative document
ref = window.open('http://mfsom.com.br/','_self',',location=no');
ref.addEventListener('loadstart', loadstartCallback);
ref.addEventListener('loadstop', loadstopCallback);
ref.addEventListener('loadloaderror', loaderrorCallback);
ref.addEventListener('exit', exitCallback);
function loadstartCallback(event) {
showSpinnerDialog();
}
function loadstopCallback(event) {
hideSpinnerDialog();
}
function loaderrorCallback(error) {
console.log('Erro ao carregar: ' + error.message)
}
function exitCallback() {
console.log('O navegador está fechado...')
}
function showSpinnerDialog() {
navigator.notification.activityStart("Carregando..");
//$.mobile.loading("show");
}
function hideSpinnerDialog() {
navigator.notification.activityStop();
//$.mobile.loading("hide");
}
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
// TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
};
As both the answers here use the activityStop() which is deprecated, use your own spinner which you use in your app to prevent InAppBrowser's blank opening screen
Open the InAppBrowser in using hidden=yes option and later in loadstop event listener show the InAppBrowser. Till then you can show your custom loader
var ref = window.open("http://m.estadao.com.br/?load-all=true", "_blank", "location=no,toolbar=no,closebuttoncaption=a,EnableViewPortScale=no,hidden=yes");
ref.addEventListener('loadstart', function() {
showLoader();//`showLoader()` is your own loader function to show loader within your app
});
ref.addEventListener('loadstop', function() {
ref.show();
hideLoader();//`hideLoader()` is your own loader function to hide loader within your app
});

Categories

Resources