4

I am working on a flutter app which requires the help of some native Android codes. To be more specific, I want to integrate an ad network named "IronSource" to serve ads in my app. But currently they do not provide a library for flutter so I wrote the required codes in java language and did a platform call to show an ad. The ad is showing successfully but I have a problem on how to listen to their callback methods that they have provided.

I will post what I have tried so far.

new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
            new MethodCallHandler() {
                @Override
                public void onMethodCall(MethodCall call, Result result) {
                    if (call.method.equals("loadInterstitialAd")) {
                      IronSource.loadInterstitial();
                    } else {
                      result.notImplemented();
                      }
                      }
            });

The above method will listen to the channel and will load the ad. However, these are some of the callback methods that are available in native library:

public void onInterstitialAdLoadFailed
public void onInterstitialAdOpened()
public void onInterstitialAdClosed()
public void onInterstitialAdShowSucceeded()

and so on...

Now I do not understand how to access these methods in flutter and write my own code.

Any idea/suggestion would be appreciated.
Thanks

Sajad Jaward
  • 247
  • 5
  • 16
  • Possible duplicate of [Flutter: How to call methods in Dart portion of the app, from the native platform using MethodChannel?](https://stackoverflow.com/questions/50187680/flutter-how-to-call-methods-in-dart-portion-of-the-app-from-the-native-platfor) – Richard Heap Mar 21 '19 at 13:45

1 Answers1

6

You can define some Integer values for onInterstitialAdLoadFailedonInterstitialAdOpenedonInterstitialAdClosedonInterstitialAdShowSucceeded and call Result.onSuccess(Object) in those callback methods. Here is the sample code:

Native part:

Result mResult;
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
    new MethodCallHandler() {
        @Override
        public void onMethodCall(MethodCall call, Result result) {
            if (call.method.equals("loadInterstitialAd")) {
              IronSource.loadInterstitial();
              mResult = result;//save the result
            } else {
              result.notImplemented();
            }
        }
    });

 public void onInterstitialAdLoadFailed(){
     mResult.success(0);
 }
 public void onInterstitialAdOpened(){
     mResult.success(1);
 }
 public void onInterstitialAdClosed(){
     mResult.success(2);
 }
 public void onInterstitialAdShowSucceeded(){
     mResult.success(3);
 }

Flutter part:

int resultCode = await loadAds();
if(resultCode == 0){ ... }
else if(resultCode == 1){ ... }
else if(resultCode == 2){ ... }
else if(resultCode == 3){ ... }
JackShen
  • 566
  • 2
  • 10