com.devblack.plugins.googleadmob
v0.0.3
Published
A custom Cordova plugin for Google AdMob integration.
Maintainers
Readme
MyGoogleAdMobPlugin
📖 Table of Contents
- ✨ Features
- 🛠️ Prerequisites
- 🚀 Installation
- ⚙️ Plugin Configuration
- 📱 Usage Guide
- 🧪 Testing
- ❓ FAQs
- 💡 Troubleshooting
- 📄 License
✨ Features
🎯 Key Capabilities
- 🎪 Banner Ads: Display and hide standard banner ads at the top or bottom of the screen
- 🎭 Interstitial Ads: Load and show full-screen ads at strategic moments (e.g., between app screens or game levels)
- 🔄 AdMob Initialization: Automatically initializes the Google Mobile Ads SDK, required for ad functionality
- ⚙️ Configurable App ID: Set your AdMob App ID during plugin installation using a Cordova variable
- 📱 Android Support: Fully tested and optimized for Android devices and emulators
- 🔮 Future iOS Support: Planned for upcoming releases
🛠️ Prerequisites
Before installing the plugin, ensure you have the following:
📋 Required Tools
- Node.js and npm: Latest LTS version
node -v && npm -v - Ionic CLI or Cordova CLI:
npm install -g @ionic/cli # or npm install -g cordova - Android SDK: Installed via Android Studio, with API level 33+
🎯 AdMob Requirements
- AdMob Account: Sign up at Google AdMob
- App ID: Create an app in AdMob to get your
ADMOB_APP_ID - Ad Unit IDs: Create banner and interstitial ad units
🏗️ Project Setup
- Ionic/Cordova Project: Working project with Android platform
ionic cordova platform add android - TypeScript: Required for Ionic Angular projects (included by default)
- AndroidX: Plugin requires AndroidX support
⚠️ Important: Add
cordova-plugin-androidxandcordova-plugin-androidx-adapterif using an older project.
🚀 Installation
Install the plugin with your AdMob App ID:
ionic cordova plugin add com.devblack.plugins.googleadmob --variable ADMOB_APP_ID="YOUR_ADMOB_APP_ID"🔄 Alternative Installation Methods
Using Cordova CLI:
cordova plugin add com.devblack.plugins.googleadmob --variable ADMOB_APP_ID="YOUR_ADMOB_APP_ID"For testing purposes:
ionic cordova plugin add com.devblack.plugins.googleadmob --variable ADMOB_APP_ID="ca-app-pub-3940256099942544~3347511713"⚙️ Plugin Configuration
📝 Configuration Details
| Setting | Description | Location |
|---------|-------------|----------|
| AdMob App ID | Set via ADMOB_APP_ID variable during installation | Installation command |
| Android Manifest | Auto-added metadata entry | platforms/android/app/src/main/AndroidManifest.xml |
| Test Ad Units | Use Google's test IDs during development | See table below |
| Gradle Dependencies | Auto-included Google Mobile Ads SDK | platforms/android/build.gradle |
🧪 Test Ad Unit IDs
⚠️ Important: Always use test ad unit IDs during development to avoid AdMob policy violations.
| Ad Type | Test Unit ID |
|---------|-------------|
| Banner | ca-app-pub-3940256099942544/6300978111 |
| Interstitial | ca-app-pub-3940256099942544/1033173712 |
🔍 Verification Steps
Check AndroidManifest.xml for the metadata entry:
<meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="YOUR_ADMOB_APP_ID"/>Internet Connection
- ✅ Ensure device has active internet connection
- ✅ Check firewall/proxy settings
AdMob App ID Issues
- ✅ Verify App ID is correctly set during installation
- ✅ Check AndroidManifest.xml for proper metadata entry
SDK Initialization
- ✅ Ensure
initialize()is called before showing ads - ✅ Wait for successful initialization callback
- ✅ Ensure
Solution Steps:
Update Dependencies
npm update ionic cordova platform remove android ionic cordova platform add androidAndroidX Migration
ionic cordova plugin add cordova-plugin-androidx ionic cordova plugin add cordova-plugin-androidx-adapterClean Build
ionic cordova clean android ionic cordova build android
Checklist:
- [ ] Switch from test ad units to production units
- [ ] Verify AdMob account is approved and active
- [ ] Check AdMob console for policy violations
- [ ] Ensure app is published and live
Solution:
Check Cordova Platform
ionic cordova platform lsVerify Plugin Installation
ionic cordova plugin lsReinstall if Missing
ionic cordova plugin add com.devblack.plugins.googleadmob --variable ADMOB_APP_ID="YOUR_APP_ID"
🔍 Debug Commands
# Check installed plugins
ionic cordova plugin ls
# View detailed build logs
ionic cordova build android --verbose
# Clean project
ionic cordova clean android
# Check platform status
ionic cordova platform ls📊 Performance Optimization
| Issue | Impact | Solution | |-------|--------|----------| | Slow ad loading | Poor UX | Preload interstitials, use banner caching | | Memory leaks | App crashes | Properly hide/destroy ads when not needed | | Battery drain | User complaints | Limit ad refresh rates, optimize ad placement |
🏆 Best Practices
📈 Ad Placement Strategy
Banner Ads
- Place at natural break points
- Avoid covering important UI elements
- Consider user navigation patterns
Interstitial Ads
- Show between natural app transitions
- Avoid interrupting user tasks
- Implement frequency capping
🎯 User Experience
- Respect User Intent: Don't show ads during critical actions
- Loading States: Show loading indicators while ads load
- Graceful Failures: Handle ad failures without breaking app flow
- Accessibility: Ensure ads don't interfere with screen readers
🔒 Privacy & Compliance
- GDPR Compliance: Implement consent mechanisms for EU users
- COPPA Compliance: Special handling for users under 13
- App Store Policies: Follow platform-specific advertising guidelines
🛠️ Advanced Configuration
🎨 Custom Ad Sizes
// Custom banner sizes (future feature)
const customBannerConfig = {
width: 320,
height: 50,
position: 'bottom'
};🔄 Ad Events Handling
// Enhanced event handling (future feature)
window.MyGoogleAdMobPlugin.on('adLoaded', (adType) => {
console.log(`${adType} ad loaded successfully`);
});
window.MyGoogleAdMobPlugin.on('adFailedToLoad', (error) => {
console.error('Ad failed to load:', error);
});📊 Analytics Integration
// Track ad performance
private trackAdEvent(eventName: string, adType: string) {
// Your analytics implementation
console.log(`Ad Event: ${eventName} - ${adType}`);
}🚀 Migration Guide
From v1.x to v2.x
Breaking Changes:
- Method signatures updated
- New initialization requirement
- Updated callback patterns
Migration Steps:
- Update TypeScript declarations
- Add initialization call
- Update method calls to new signatures
- Test thoroughly on device
🤝 Contributing
We welcome contributions! Here's how you can help:
🐛 Bug Reports
- Use GitHub Issues
- Provide detailed reproduction steps
- Include device/platform information
🔧 Feature Requests
- Describe the use case
- Explain expected behavior
- Consider implementation complexity
📝 Documentation
- Fix typos or unclear sections
- Add examples for common use cases
- Improve code comments
💻 Code Contributions
- Fork the repository
- Create feature branches
- Follow coding standards
- Include tests where possible
📞 Support
🆘 Getting Help
- Check Documentation: Review this README thoroughly
- Search Issues: Look for similar problems in GitHub Issues
- Community Forums: Ask questions in Ionic/Cordova communities
- Professional Support: Consider paid consulting for complex implementations
📧 Contact Options
- GitHub Issues: For bugs and feature requests
- Stack Overflow: Tag with
ionic,cordova,admob - Ionic Forum: Community support and discussions
🔮 Roadmap
🎯 Upcoming Features
- [ ] iOS Support: Full iOS implementation
- [ ] Rewarded Ads: Video ads with rewards
- [ ] Native Ads: Seamless content integration
- [ ] Advanced Targeting: Demographic and interest-based targeting
- [ ] A/B Testing: Built-in ad performance testing
- [ ] Analytics Dashboard: Comprehensive performance metrics
📅 Version History
| Version | Date | Changes | |---------|------|---------| | v0.0.3 | 2025-07-03 | Update readme.md file | | v0.0.2 | 2025-07-03 | Added interstitial ads, bug fixes and added readme.md file | | v0.0.1 | 2025-07-02 | Initial release, banner ads only |
📄 License
MIT License
Copyright (c) 2024 MyGoogleAdMobPlugin Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.🙏 Acknowledgments
- Google AdMob Team: For providing the mobile advertising platform
- Ionic Team: For the amazing cross-platform framework
- Apache Cordova: For enabling hybrid mobile development
- Community Contributors: For bug reports, feature requests, and improvements
⬆️ Back to Top
📱 Usage Guide
Step 1: TypeScript Declaration
Create type definitions for TypeScript support and IDE auto-completion.
📁 File Structure
your-ionic-project/
├── src/
│ ├── typings/
│ │ └── MyGoogleAdMobPlugin.d.ts
│ └── ...
└── tsconfig.app.json📝 Create Declaration File
Path: src/typings/MyGoogleAdMobPlugin.d.ts
/**
* MyGoogleAdMobPlugin - Cordova Plugin Type Definitions
* Provides TypeScript support for Google AdMob integration
*/
interface CordovaPlugins {
MyGoogleAdMobPlugin: {
/**
* Initializes the Google Mobile Ads SDK
* @param successCallback Called on successful initialization
* @param errorCallback Called on failure with error details
*/
initialize(
successCallback: () => void,
errorCallback: (error: any) => void
): void;
/**
* Displays a banner ad at specified position
* @param adUnitId AdMob banner ad unit ID
* @param position Screen position - 'top' or 'bottom'
* @param successCallback Called on successful display
* @param errorCallback Called on failure with error details
*/
showBannerAd(
adUnitId: string,
position: 'top' | 'bottom',
successCallback: () => void,
errorCallback: (error: any) => void
): void;
/**
* Hides the currently displayed banner ad
* @param successCallback Called on successful hide
* @param errorCallback Called on failure with error details
*/
hideBannerAd(
successCallback: () => void,
errorCallback: (error: any) => void
): void;
/**
* Loads an interstitial ad for later display
* @param adUnitId AdMob interstitial ad unit ID
* @param successCallback Called on successful load
* @param errorCallback Called on failure with error details
*/
loadInterstitialAd(
adUnitId: string,
successCallback: () => void,
errorCallback: (error: any) => void
): void;
/**
* Shows a previously loaded interstitial ad
* @param successCallback Called on successful display
* @param errorCallback Called on failure with error details
*/
showInterstitialAd(
successCallback: () => void,
errorCallback: (error: any) => void
): void;
};
}
interface Window {
MyGoogleAdMobPlugin: CordovaPlugins['MyGoogleAdMobPlugin'];
}⚙️ Update TypeScript Configuration
Path: tsconfig.app.json
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "../../out-tsc/app",
"types": []
},
"include": [
"src/**/*.d.ts",
"src/typings/**/*.d.ts"
],
"exclude": [
"node_modules"
]
}Step 2: Component Implementation
Implement the plugin functionality in your main app component.
Path: src/app/app.component.ts
import { Component, OnInit, NgZone } from '@angular/core';
import { Platform } from '@ionic/angular';
declare var window: Window;
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss'],
standalone: false,
})
export class AppComponent implements OnInit {
// 🧪 Test Ad Unit IDs (Replace with your production IDs)
private readonly TEST_BANNER_ID = 'ca-app-pub-3940256099942544/6300978111';
private readonly TEST_INTERSTITIAL_ID = 'ca-app-pub-3940256099942544/1033173712';
// 📊 State Management
private interstitialLoaded = false;
public adStatus = {
bannerVisible: false,
interstitialReady: false,
sdkInitialized: false
};
constructor(
private platform: Platform,
private zone: NgZone
) {}
async ngOnInit() {
console.log('🚀 AppComponent: Starting AdMob initialization...');
await this.platform.ready();
if (this.isCordovaEnvironment()) {
console.log('📱 Cordova environment detected. Initializing AdMob...');
this.initializeAdMob();
} else {
console.log('🌐 Browser environment detected. Ads will be simulated.');
}
}
// 🔍 Environment Detection
private isCordovaEnvironment(): boolean {
return !!(window as any).cordova && window.MyGoogleAdMobPlugin;
}
// 🎯 AdMob Initialization
private initializeAdMob(): void {
this.zone.run(() => {
window.MyGoogleAdMobPlugin.initialize(
() => {
console.log('✅ AdMob SDK initialized successfully!');
this.adStatus.sdkInitialized = true;
},
(error: any) => {
console.error('❌ AdMob SDK initialization failed:', error);
this.adStatus.sdkInitialized = false;
}
);
});
}
// 📱 Banner Ad Methods
public showBannerAd(
adUnitId: string = this.TEST_BANNER_ID,
position: 'top' | 'bottom' = 'bottom'
): void {
if (!this.isCordovaEnvironment()) {
this.simulateBannerAd(adUnitId, position);
return;
}
console.log(`📢 Showing banner ad at ${position}...`);
this.zone.run(() => {
window.MyGoogleAdMobPlugin.showBannerAd(
adUnitId,
position,
() => {
console.log('✅ Banner ad displayed successfully!');
this.adStatus.bannerVisible = true;
},
(error: any) => {
console.error('❌ Failed to show banner ad:', error);
this.adStatus.bannerVisible = false;
}
);
});
}
public hideBannerAd(): void {
if (!this.isCordovaEnvironment()) {
this.removeBrowserBannerAd();
return;
}
console.log('🙈 Hiding banner ad...');
this.zone.run(() => {
window.MyGoogleAdMobPlugin.hideBannerAd(
() => {
console.log('✅ Banner ad hidden successfully!');
this.adStatus.bannerVisible = false;
},
(error: any) => {
console.error('❌ Failed to hide banner ad:', error);
}
);
});
}
// 🎬 Interstitial Ad Methods
public loadInterstitialAd(adUnitId: string = this.TEST_INTERSTITIAL_ID): void {
if (!this.isCordovaEnvironment()) {
this.simulateInterstitialLoad();
return;
}
console.log('📥 Loading interstitial ad...');
this.adStatus.interstitialReady = false;
this.zone.run(() => {
window.MyGoogleAdMobPlugin.loadInterstitialAd(
adUnitId,
() => {
console.log('✅ Interstitial ad loaded successfully!');
this.adStatus.interstitialReady = true;
this.interstitialLoaded = true;
},
(error: any) => {
console.error('❌ Failed to load interstitial ad:', error);
this.adStatus.interstitialReady = false;
this.interstitialLoaded = false;
}
);
});
}
public showInterstitialAd(): void {
if (!this.isCordovaEnvironment()) {
this.simulateInterstitialShow();
return;
}
if (!this.interstitialLoaded) {
console.warn('⚠️ Interstitial ad not loaded. Please load first.');
return;
}
console.log('🎬 Showing interstitial ad...');
this.zone.run(() => {
window.MyGoogleAdMobPlugin.showInterstitialAd(
() => {
console.log('✅ Interstitial ad displayed successfully!');
this.adStatus.interstitialReady = false;
this.interstitialLoaded = false;
},
(error: any) => {
console.error('❌ Failed to show interstitial ad:', error);
}
);
});
}
// 🌐 Browser Simulation Methods
private simulateBannerAd(adUnitId: string, position: 'top' | 'bottom'): void {
console.log('🎭 Simulating banner ad in browser...');
this.removeBrowserBannerAd();
const banner = document.createElement('div');
banner.id = 'web-ad-banner';
banner.style.cssText = `
position: fixed;
${position === 'top' ? 'top: 0;' : 'bottom: 0;'}
left: 0;
width: 100%;
height: 50px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
display: flex;
align-items: center;
justify-content: center;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
font-size: 14px;
font-weight: 500;
${position === 'bottom' ? 'border-top: 1px solid rgba(255,255,255,0.2);' : ''}
${position === 'top' ? 'border-bottom: 1px solid rgba(255,255,255,0.2);' : ''}
z-index: 10000;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
animation: slideIn 0.3s ease-out;
`;
banner.innerHTML = `🎯 Simulated Banner Ad • ${position.toUpperCase()} • ID: ${adUnitId.substring(0, 20)}...`;
document.body.appendChild(banner);
// Add CSS animation
const style = document.createElement('style');
style.textContent = `
@keyframes slideIn {
from { transform: translateY(${position === 'top' ? '-100%' : '100%'}); }
to { transform: translateY(0); }
}
`;
document.head.appendChild(style);
this.adStatus.bannerVisible = true;
}
private removeBrowserBannerAd(): void {
const existingAd = document.getElementById('web-ad-banner');
if (existingAd) {
existingAd.remove();
this.adStatus.bannerVisible = false;
}
}
private simulateInterstitialLoad(): void {
console.log('🎭 Simulating interstitial ad load...');
setTimeout(() => {
this.adStatus.interstitialReady = true;
this.interstitialLoaded = true;
console.log('✅ Simulated interstitial ad loaded!');
}, 1000);
}
private simulateInterstitialShow(): void {
if (!this.interstitialLoaded) {
alert('⚠️ Interstitial ad not loaded. Please load first.');
return;
}
console.log('🎭 Simulating interstitial ad show...');
// Create fullscreen overlay
const overlay = document.createElement('div');
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 20000;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
animation: fadeIn 0.3s ease-out;
`;
overlay.innerHTML = `
<h2 style="margin: 0 0 20px 0; font-size: 24px;">🎬 Simulated Interstitial Ad</h2>
<p style="margin: 0 0 30px 0; text-align: center; font-size: 16px;">
This would be a full-screen ad<br>
<small>Click anywhere to close</small>
</p>
<div style="width: 50px; height: 50px; border: 3px solid white; border-radius: 50%;
border-top-color: transparent; animation: spin 1s linear infinite;"></div>
`;
// Add CSS animations
const style = document.createElement('style');
style.textContent = `
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
`;
document.head.appendChild(style);
document.body.appendChild(overlay);
// Auto-close after 3 seconds or on click
const closeAd = () => {
overlay.remove();
this.adStatus.interstitialReady = false;
this.interstitialLoaded = false;
};
overlay.addEventListener('click', closeAd);
setTimeout(closeAd, 3000);
}
}Step 3: HTML Template
Create an intuitive user interface for testing ad functionality.
Path: src/app/app.component.html
<ion-app>
<ion-router-outlet></ion-router-outlet>
<!-- 🎮 Ad Testing Control Panel -->
<div class="ad-control-panel">
<!-- 📊 Status Indicators -->
<div class="status-bar">
<div class="status-item" [class.active]="adStatus.sdkInitialized">
<ion-icon name="checkmark-circle" *ngIf="adStatus.sdkInitialized"></ion-icon>
<ion-icon name="close-circle" *ngIf="!adStatus.sdkInitialized"></ion-icon>
<span>SDK</span>
</div>
<div class="status-item" [class.active]="adStatus.bannerVisible">
<ion-icon name="checkmark-circle" *ngIf="adStatus.bannerVisible"></ion-icon>
<ion-icon name="close-circle" *ngIf="!adStatus.bannerVisible"></ion-icon>
<span>Banner</span>
</div>
<div class="status-item" [class.active]="adStatus.interstitialReady">
<ion-icon name="checkmark-circle" *ngIf="adStatus.interstitialReady"></ion-icon>
<ion-icon name="close-circle" *ngIf="!adStatus.interstitialReady"></ion-icon>
<span>Interstitial</span>
</div>
</div>
<!-- 🎯 Banner Ad Controls -->
<div class="control-section">
<h3>📱 Banner Ads</h3>
<div class="button-group">
<ion-button
expand="block"
fill="outline"
(click)="showBannerAd(undefined, 'top')">
<ion-icon name="arrow-up" slot="start"></ion-icon>
Show Top Banner
</ion-button>
<ion-button
expand="block"
fill="outline"
(click)="showBannerAd(undefined, 'bottom')">
<ion-icon name="arrow-down" slot="start"></ion-icon>
Show Bottom Banner
</ion-button>
<ion-button
expand="block"
fill="clear"
color="medium"
(click)="hideBannerAd()">
<ion-icon name="eye-off" slot="start"></ion-icon>
Hide Banner
</ion-button>
</div>
</div>
<!-- 🎬 Interstitial Ad Controls -->
<div class="control-section">
<h3>🎬 Interstitial Ads</h3>
<div class="button-group">
<ion-button
expand="block"
fill="outline"
(click)="loadInterstitialAd()">
<ion-icon name="download" slot="start"></ion-icon>
Load Interstitial
</ion-button>
<ion-button
expand="block"
[disabled]="!adStatus.interstitialReady"
(click)="showInterstitialAd()">
<ion-icon name="play" slot="start"></ion-icon>
Show Interstitial
</ion-button>
</div>
</div>
</div>
</ion-app>🎨 Add Styling
Path: src/app/app.component.scss
.ad-control-panel {
position: fixed;
bottom: 0;
left: 0;
right: 0;
background: var(--ion-background-color, #fff);
border-top: 1px solid var(--ion-border-color, #e0e0e0);
padding: 16px;
z-index: 1000;
box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
.status-bar {
display: flex;
justify-content: space-around;
margin-bottom: 16px;
padding: 8px;
background: var(--ion-color-light, #f5f5f5);
border-radius: 8px;
.status-item {
display: flex;
flex-direction: column;
align-items: center;
font-size: 12px;
color: var(--ion-color-medium, #666);
&.active {
color: var(--ion-color-success, #2dd36f);
}
ion-icon {
font-size: 20px;
margin-bottom: 4px;
}
}
}
.control-section {
margin-bottom: 16px;
&:last-child {
margin-bottom: 0;
}
h3 {
margin: 0 0 12px 0;
font-size: 16px;
font-weight: 600;
color: var(--ion-color-primary, #3880ff);
}
.button-group {
display: flex;
flex-direction: column;
gap: 8px;
}
}
}
// 📱 Responsive Design
@media (min-width: 768px) {
.ad-control-panel {
.control-section {
.button-group {
flex-direction: row;
ion-button {
flex: 1;
}
}
}
}
}🧪 Testing
🎯 Testing Strategy
- Use Test Ad Units: Always use Google's test ad unit IDs during development
- Test on Real Devices: Run on Android devices or emulators for accurate results
- Monitor Logs: Use debugging tools to track ad performance
- Browser Simulation: Test UI interactions with
ionic serve
📱 Testing Commands
# Build and run on Android device
ionic cordova run android --device
# Build and run on Android emulator
ionic cordova run android
# Test in browser (ads simulated)
ionic serve🔍 Debugging Tools
| Tool | Purpose | Command |
|------|---------|---------|
| Chrome DevTools | Debug web view | chrome://inspect |
| Android Studio Logcat | View native logs | Built-in Android Studio |
| Ionic DevApp | Live reload testing | Install from app stores |
✅ Testing Checklist
- [ ] Banner ads appear at correct positions (top/bottom)
- [ ] Banner ads can be hidden successfully
- [ ] Interstitial ads load without errors
- [ ] Interstitial ads display in fullscreen
- [ ] Ads respect test vs. production unit IDs
- [ ] Error handling works correctly
- [ ] UI remains responsive during ad operations
❓ FAQs
Currently, the plugin is optimized for Android devices and emulators. iOS support is actively being developed and will be available in future releases. Check the repository for updates on iOS compatibility.
AdMob ads require a native mobile environment to function properly. When testing with ionic serve, the plugin automatically simulates ads using HTML elements and JavaScript alerts. This allows you to test your UI and ad integration logic without needing a device.
- Create AdMob Account: Sign up at Google AdMob
- Add Your App: Create a new app in the AdMob console
- Get App ID: Found in App Settings → App ID
- Create Ad Units: Create banner and interstitial ad units
- Copy Unit IDs: Use the generated ad unit IDs in your code
- Check Declaration File: Ensure
MyGoogleAdMobPlugin.d.tsexists insrc/typings/ - Verify tsconfig.json: Confirm
src/typings/**/*.d.tsis included - Restart IDE: Close and reopen your IDE/editor
- Clean Build: Run
ionic cordova clean androidand rebuild
Yes! While this guide focuses on Ionic Angular, the plugin works with:
- Ionic React
- Ionic Vue
- Plain Cordova
- PhoneGap
The TypeScript declarations and implementation details will vary based on your framework choice.
The plugin itself is free and open-source. However, you'll need:
- AdMob Account: Free to create
- Revenue Sharing: AdMob takes a percentage of ad revenue
- Developer Account: May need Google Play Console account for publishing
💡 Troubleshooting
🚨 Common Issues & Solutions
Cause: Incorrect method signatures in native code.
Solution:
- Clean your project:
ionic cordova clean android - Remove and re-add the plugin:
ionic cordova plugin remove com.devblack.plugins.googleadmob ionic cordova plugin add com.devblack.plugins.googleadmob --variable ADMOB_APP_ID="YOUR_APP_ID" - Rebuild:
ionic cordova build android
Possible Causes & Solutions:
Incorrect Ad Unit IDs
- ✅ Verify your ad unit IDs are correct
- ✅ Use test IDs during development
Internet Connection
- ✅ Ensure device has active internet connection
- ✅ Check firewall/proxy settings
AdMob App ID Issues
- ✅ Verify App ID is correctly set during installation
- ✅ Check AndroidManifest.xml for proper metadata entry
SDK Initialization
- ✅ Ensure
initialize()is called before showing ads - ✅ Wait for successful initialization callback
- ✅ Ensure
