Skip to content

Commit

Permalink
Implement interstitial ads on Android
Browse files Browse the repository at this point in the history
  • Loading branch information
YoussefKababe committed Dec 8, 2018
1 parent cf578e1 commit 51bc5a1
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.shatsy.admobflutter

import android.content.Context
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.InterstitialAd
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel

class AdmobInterstitial(private val context: Context): MethodChannel.MethodCallHandler {
companion object {
val allAds: MutableMap<Int, InterstitialAd> = mutableMapOf()
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when(call.method) {
"load" -> {
val id = call.argument<Int>("id")
val adUnitId = call.argument<String>("adUnitId")
val adRequest = AdRequest.Builder().build()

allAds[id!!] = InterstitialAd(context)
allAds[id]!!.adUnitId = adUnitId
allAds[id]?.loadAd(adRequest)
result.success(null)
}
"isLoaded" -> {
val id = call.argument<Int>("id")

if (allAds[id]!!.isLoaded) {
result.success(true)
} else result.success(false)
}
"show" -> {
val id = call.argument<Int>("id")

if (allAds[id]!!.isLoaded) {
allAds[id]!!.show()
} else result.error(null, null, null)
}
"dispose" -> {
val id = call.argument<Int>("id")

allAds.remove(id)
}
else -> result.notImplemented()
}
}
}
46 changes: 46 additions & 0 deletions lib/src/admob_interstitial.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import 'package:flutter/services.dart';
import 'package:meta/meta.dart';

class AdmobInterstitial {
static Map<int, AdmobInterstitial> _allAds = <int, AdmobInterstitial>{};
static const MethodChannel _channel =
const MethodChannel('admob_flutter/interstitial');

int id;
final String adUnitId;

AdmobInterstitial({@required this.adUnitId}) {
id = hashCode;
_allAds[id] = this;
}

Future<bool> get isLoaded async {
final bool result = await _channel.invokeMethod('isLoaded', <String, dynamic>{
'id': id,
});
return result;
}

void loadAd() {
_channel.invokeMethod('load', <String, dynamic>{
'id': id,
'adUnitId': adUnitId,
});
}

void show() async {
if (await isLoaded == true) {
_channel.invokeMethod('show', <String, dynamic>{
'id': id,
});
}
}

void dispose() async {
await _channel.invokeMethod('dispose', <String, dynamic>{
'id': id,
});

_allAds.remove(id);
}
}

0 comments on commit 51bc5a1

Please sign in to comment.