Android और iOS में नेटिव सेटअप

नेटिव विज्ञापन, उपयोगकर्ताओं को दिखाए जाते हैं. ये प्लैटफ़ॉर्म के यूज़र इंटरफ़ेस (यूआई) कॉम्पोनेंट का इस्तेमाल करते हैं. उदाहरण के लिए, Android पर View या iOS के लिए UIView.

इस गाइड में प्लैटफ़ॉर्म के खास कोड का इस्तेमाल करके, नेटिव विज्ञापनों को लोड करने, दिखाने, और पसंद के मुताबिक बनाने का तरीका बताया गया है.

ज़रूरी शर्तें

हमेशा टेस्ट विज्ञापनों से टेस्ट करें

अपने ऐप्लिकेशन बनाते और टेस्ट करते समय पक्का करें कि आप लाइव, प्रोडक्शन विज्ञापनों के बजाय टेस्ट विज्ञापनों का इस्तेमाल करें. नेटिव विज्ञापनों के लिए हमारे खास टेस्ट विज्ञापन यूनिट आईडी का इस्तेमाल करना, टेस्ट विज्ञापन को लोड करने का सबसे आसान तरीका है:

Android

ca-app-pub-3940256099942544/2247696110

iOS

ca-app-pub-3940256099942544/3986624511

टेस्ट विज्ञापन यूनिट, हर अनुरोध पर टेस्ट विज्ञापन दिखाने के लिए कॉन्फ़िगर की जाती हैं. इसलिए, कोडिंग, टेस्टिंग, और डीबग करते समय, अपने ऐप्लिकेशन में उनका इस्तेमाल किया जा सकता है—अपना ऐप्लिकेशन पब्लिश करने से पहले, पक्का करें कि आपने उन्हें अपने विज्ञापन यूनिट आईडी से बदल दिया हो.

प्लैटफ़ॉर्म के हिसाब से सेट अप

अपने नेटिव विज्ञापन बनाने के लिए, आपको iOS और Android के लिए प्लैटफ़ॉर्म के हिसाब से कोड लिखना होगा. इसके बाद, आपको Dart लागू करने वाले कोड में बदलाव करना होगा, ताकि आप नेटिव कोड में किए गए बदलावों का फ़ायदा ले सकें.

Android

प्लग इन इंपोर्ट करें

Android पर Google Mobile Ads प्लगिन को लागू करने के लिए, NativeAdFactory एपीआई को लागू करने वाली क्लास की ज़रूरत होती है. अपने Android प्रोजेक्ट में इस एपीआई का रेफ़रंस देने के लिए, अपनी settings.gradle में ये लाइनें जोड़ें:

def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
def plugins = new Properties()
def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
if (pluginsFile.exists()) {
    pluginsFile.withInputStream { stream -> plugins.load(stream) }
}

plugins.each { name, path ->
    def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
    include ":$name"
    project(":$name").projectDir = pluginDirectory
}

NativeAdFactory लागू करें

इसके बाद, एक ऐसी क्लास बनाएं जो NativeAdFactory को लागू करती हो और createNativeAd() तरीके को बदल देती हो.

package io.flutter.plugins.googlemobileadsexample;

import android.graphics.Color;
import android.view.LayoutInflater;
import android.widget.TextView;
import com.google.android.gms.ads.nativead.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdView;
import io.flutter.plugins.googlemobileads.GoogleMobileAdsPlugin.NativeAdFactory;
import java.util.Map;

/**
 * my_native_ad.xml can be found at
 * github.com/googleads/googleads-mobile-flutter/blob/main/packages/google_mobile_ads/
 *     example/android/app/src/main/res/layout/my_native_ad.xml
 */
class NativeAdFactoryExample implements NativeAdFactory {
  private final LayoutInflater layoutInflater;

  NativeAdFactoryExample(LayoutInflater layoutInflater) {
    this.layoutInflater = layoutInflater;
  }

  @Override
  public NativeAdView createNativeAd(
      NativeAd nativeAd, Map<String, Object> customOptions) {
    final NativeAdView adView =
        (NativeAdView) layoutInflater.inflate(R.layout.my_native_ad, null);

    // Set the media view.
    adView.setMediaView((MediaView) adView.findViewById(R.id.ad_media));

    // Set other ad assets.
    adView.setHeadlineView(adView.findViewById(R.id.ad_headline));
    adView.setBodyView(adView.findViewById(R.id.ad_body));
    adView.setCallToActionView(adView.findViewById(R.id.ad_call_to_action));
    adView.setIconView(adView.findViewById(R.id.ad_app_icon));
    adView.setPriceView(adView.findViewById(R.id.ad_price));
    adView.setStarRatingView(adView.findViewById(R.id.ad_stars));
    adView.setStoreView(adView.findViewById(R.id.ad_store));
    adView.setAdvertiserView(adView.findViewById(R.id.ad_advertiser));

    // The headline and mediaContent are guaranteed to be in every NativeAd.
    ((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());
    adView.getMediaView().setMediaContent(nativeAd.getMediaContent());

    // These assets aren't guaranteed to be in every NativeAd, so it's important to
    // check before trying to display them.
    if (nativeAd.getBody() == null) {
      adView.getBodyView().setVisibility(View.INVISIBLE);
    } else {
      adView.getBodyView().setVisibility(View.VISIBLE);
      ((TextView) adView.getBodyView()).setText(nativeAd.getBody());
    }

    if (nativeAd.getCallToAction() == null) {
      adView.getCallToActionView().setVisibility(View.INVISIBLE);
    } else {
      adView.getCallToActionView().setVisibility(View.VISIBLE);
      ((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
    }

    if (nativeAd.getIcon() == null) {
      adView.getIconView().setVisibility(View.GONE);
    } else {
      ((ImageView) adView.getIconView()).setImageDrawable(nativeAd.getIcon().getDrawable());
      adView.getIconView().setVisibility(View.VISIBLE);
    }

    if (nativeAd.getPrice() == null) {
      adView.getPriceView().setVisibility(View.INVISIBLE);
    } else {
      adView.getPriceView().setVisibility(View.VISIBLE);
      ((TextView) adView.getPriceView()).setText(nativeAd.getPrice());
    }

    if (nativeAd.getStore() == null) {
      adView.getStoreView().setVisibility(View.INVISIBLE);
    } else {
      adView.getStoreView().setVisibility(View.VISIBLE);
      ((TextView) adView.getStoreView()).setText(nativeAd.getStore());
    }

    if (nativeAd.getStarRating() == null) {
      adView.getStarRatingView().setVisibility(View.INVISIBLE);
    } else {
      ((RatingBar) adView.getStarRatingView()).setRating(nativeAd.getStarRating()
          .floatValue());
      adView.getStarRatingView().setVisibility(View.VISIBLE);
    }

    if (nativeAd.getAdvertiser() == null) {
      adView.getAdvertiserView().setVisibility(View.INVISIBLE);
    } else {
      adView.getAdvertiserView().setVisibility(View.VISIBLE);
      ((TextView) adView.getAdvertiserView()).setText(nativeAd.getAdvertiser());
    }

    // This method tells the Google Mobile Ads SDK that you have finished populating your
    // native ad view with this native ad.
    adView.setNativeAd(nativeAd);

    return adView;
  }
}

NativeAdView लेआउट को कॉन्फ़िगर करने के उदाहरण के लिए, my_native_ad.xml देखें.

अपना NativeAdFactory रजिस्टर करें

MainActivity.configureFlutterEngine(FlutterEngine) को कॉल करते समय, हर NativeAdFactory लागू करने के लिए, एक factoryId, एक यूनीक String आइडेंटिफ़ायर के साथ रजिस्टर होना ज़रूरी है. बाद में, Dart कोड से किसी नेटिव विज्ञापन को इंस्टैंशिएट करने पर, factoryId का इस्तेमाल किया जाएगा.

आपके ऐप्लिकेशन में इस्तेमाल होने वाले हर यूनीक नेटिव विज्ञापन लेआउट के लिए, NativeAdFactory को लागू और रजिस्टर किया जा सकता है. हालांकि, कोई एक लेआउट, सभी लेआउट को हैंडल कर सकता है.

ध्यान दें कि add-to-ऐप्लिकेशन बनाते समय, NativeAdFactory को cleanUpFlutterEngine(engine) में भी रजिस्टर नहीं किया जाना चाहिए.

NativeAdFactoryExample बनाने के बाद, अपने MainActivity को इस तरह सेट अप करें:

package my.app.path;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.googlemobileads.GoogleMobileAdsPlugin;

public class MainActivity extends FlutterActivity {
  @Override
  public void configureFlutterEngine(FlutterEngine flutterEngine) {
    flutterEngine.getPlugins().add(new GoogleMobileAdsPlugin());
    super.configureFlutterEngine(flutterEngine);

    GoogleMobileAdsPlugin.registerNativeAdFactory(flutterEngine,
        "adFactoryExample", NativeAdFactoryExample());
  }

  @Override
  public void cleanUpFlutterEngine(FlutterEngine flutterEngine) {
    GoogleMobileAdsPlugin.unregisterNativeAdFactory(flutterEngine, "adFactoryExample");
  }
}

iOS

NativeAdFactory लागू करें

iOS में Google Mobile Ads प्लगिन को लागू करने के लिए, FLTNativeAdFactory एपीआई को लागू करने वाली क्लास की ज़रूरत होती है. ऐसी क्लास बनाएं जो NativeAdFactory को लागू करती हो और createNativeAd() तरीके को लागू करती हो.

#import "FLTGoogleMobileAdsPlugin.h"

/**
 * The example NativeAdView.xib can be found at
 * github.com/googleads/googleads-mobile-flutter/blob/main/packages/google_mobile_ads/
 *     example/ios/Runner/NativeAdView.xib
 */
@interface NativeAdFactoryExample : NSObject <FLTNativeAdFactory>
@end

@implementation NativeAdFactoryExample
- (GADNativeAdView *)createNativeAd:(GADNativeAd *)nativeAd
                      customOptions:(NSDictionary *)customOptions {
  // Create and place the ad in the view hierarchy.
  GADNativeAdView *adView =
      [[NSBundle mainBundle] loadNibNamed:@"NativeAdView" owner:nil options:nil].firstObject;

  // Populate the native ad view with the native ad assets.
  // The headline is guaranteed to be present in every native ad.
  ((UILabel *)adView.headlineView).text = nativeAd.headline;

  // These assets are not guaranteed to be present. Check that they are before
  // showing or hiding them.
  ((UILabel *)adView.bodyView).text = nativeAd.body;
  adView.bodyView.hidden = nativeAd.body ? NO : YES;

  [((UIButton *)adView.callToActionView) setTitle:nativeAd.callToAction
                                         forState:UIControlStateNormal];
  adView.callToActionView.hidden = nativeAd.callToAction ? NO : YES;

  ((UIImageView *)adView.iconView).image = nativeAd.icon.image;
  adView.iconView.hidden = nativeAd.icon ? NO : YES;

  ((UILabel *)adView.storeView).text = nativeAd.store;
  adView.storeView.hidden = nativeAd.store ? NO : YES;

  ((UILabel *)adView.priceView).text = nativeAd.price;
  adView.priceView.hidden = nativeAd.price ? NO : YES;

  ((UILabel *)adView.advertiserView).text = nativeAd.advertiser;
  adView.advertiserView.hidden = nativeAd.advertiser ? NO : YES;

  // In order for the SDK to process touch events properly, user interaction
  // should be disabled.
  adView.callToActionView.userInteractionEnabled = NO;

  // Associate the native ad view with the native ad object. This is
  // required to make the ad clickable.
  // Note: this should always be done after populating the ad views.
  adView.nativeAd = nativeAd;

  return adView;
}
@end

GADNativeAdView लेआउट को कॉन्फ़िगर करने के उदाहरण के लिए, NativeAdView.xib देखें.

अपना NativeAdFactory रजिस्टर करें

हर FLTNativeAdFactory को registerNativeAdFactory:factoryId:nativeAdFactory: में, एक factoryId, एक यूनीक String आइडेंटिफ़ायर, के साथ रजिस्टर करना ज़रूरी है. Dart कोड से किसी नेटिव विज्ञापन को इंस्टैंशिएट करते समय factoryId का इस्तेमाल किया जाएगा.

आपके ऐप्लिकेशन में इस्तेमाल होने वाले हर यूनीक विज्ञापन लेआउट के लिए, FLTNativeAdFactory को लागू और रजिस्टर किया जा सकता है. हालांकि, कोई एक विज्ञापन लेआउट, सभी लेआउट को मैनेज कर सकता है.

FLTNativeAdFactory बनाने के बाद, अपने AppDelegate को इस तरह सेट अप करें:

#import "FLTGoogleMobileAdsPlugin.h"
#import "NativeAdFactoryExample.h"

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
      didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];

  // Must be added after GeneratedPluginRegistrant registerWithRegistry:self];
  // is called.
  NativeAdFactoryExample *nativeAdFactory = [[NativeAdFactoryExample alloc] init];
  [FLTGoogleMobileAdsPlugin registerNativeAdFactory:self
                                          factoryId:@"adFactoryExample"
                                    nativeAdFactory:nativeAdFactory];

  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end

विज्ञापन लोड करें

प्लैटफ़ॉर्म के हिसाब से कोड जोड़ने के बाद, विज्ञापन लोड करने के लिए Dart की मदद लें. पक्का करें कि factoryID पहले रजिस्टर किए गए आईडी से मेल खाता हो.

class NativeExampleState extends State<NativeExample> {
  NativeAd? _nativeAd;
  bool _nativeAdIsLoaded = false;

 // TODO: replace this test ad unit with your own ad unit.
 final String _adUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/2247696110'
      : 'ca-app-pub-3940256099942544/3986624511';

  /// Loads a native ad.
  void loadAd() {
    _nativeAd = NativeAd(
        adUnitId: _adUnitId,
        // Factory ID registered by your native ad factory implementation.
        factoryId: 'adFactoryExample',
        listener: NativeAdListener(
          onAdLoaded: (ad) {
            print('$NativeAd loaded.');
            setState(() {
              _nativeAdIsLoaded = true;
            });
          },
          onAdFailedToLoad: (ad, error) {
            // Dispose the ad here to free resources.
            print('$NativeAd failedToLoad: $error');
            ad.dispose();
          },
        ),
        request: const AdRequest(),
        // Optional: Pass custom options to your native ad factory implementation.
        customOptions: {'custom-option-1', 'custom-value-1'}
    );
    _nativeAd.load();
  }
}

नेटिव विज्ञापन इवेंट

नेटिव विज्ञापन इंटरैक्शन से जुड़े इवेंट की सूचना पाने के लिए, विज्ञापन की listener प्रॉपर्टी का इस्तेमाल करें. इसके बाद, विज्ञापन इवेंट कॉलबैक पाने के लिए, NativeAdListener लागू करें.

class NativeExampleState extends State<NativeExample> {
  NativeAd? _nativeAd;
  bool _nativeAdIsLoaded = false;

 // TODO: replace this test ad unit with your own ad unit.
 final String _adUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/2247696110'
      : 'ca-app-pub-3940256099942544/3986624511';

  /// Loads a native ad.
  void loadAd() {
    _nativeAd = NativeAd(
        adUnitId: _adUnitId,
        // Factory ID registered by your native ad factory implementation.
        factoryId: 'adFactoryExample',
        listener: NativeAdListener(
          onAdLoaded: (ad) {
            print('$NativeAd loaded.');
            setState(() {
              _nativeAdIsLoaded = true;
            });
          },
          onAdFailedToLoad: (ad, error) {
            // Dispose the ad here to free resources.
            print('$NativeAd failedToLoad: $error');
            ad.dispose();
          },
          // Called when a click is recorded for a NativeAd.
          onAdClicked: (ad) {},
          // Called when an impression occurs on the ad.
          onAdImpression: (ad) {},
          // Called when an ad removes an overlay that covers the screen.
          onAdClosed: (ad) {},
          // Called when an ad opens an overlay that covers the screen.
          onAdOpened: (ad) {},
          // For iOS only. Called before dismissing a full screen view
          onAdWillDismissScreen: (ad) {},
          // Called when an ad receives revenue value.
          onPaidEvent: (ad, valueMicros, precision, currencyCode) {},
        ),
        request: const AdRequest(),
        // Optional: Pass custom options to your native ad factory implementation.
        customOptions: {'custom-option-1', 'custom-value-1'}
    );
    _nativeAd.load();
        
  }
}

Display Network में दिखने वाला विज्ञापन

NativeAd को विजेट के तौर पर दिखाने के लिए, आपको load() को कॉल करने के बाद, काम करने वाले विज्ञापन के साथ AdWidget को इंस्टैंशिएट करना होगा. load() को कॉल करने से पहले, विजेट बनाया जा सकता है. हालांकि, विजेट को विजेट ट्री में जोड़ने से पहले, load() को कॉल करना ज़रूरी है.

AdWidget को Flutter की Widget क्लास से इनहेरिट करता है और इसे किसी भी दूसरे विजेट की तरह इस्तेमाल किया जा सकता है. iOS पर, विजेट को किसी खास चौड़ाई और ऊंचाई वाले कंटेनर में रखें. नहीं तो, हो सकता है कि आपका विज्ञापन न दिखे.

final Container adContainer = Container(
  alignment: Alignment.center,
  child: AdWidget adWidget = AdWidget(ad: _nativeAd!),
  width: WIDTH,
  height: HEIGHT,
);

विज्ञापन नष्ट करें

अगर आपको NativeAd के ऐक्सेस की ज़रूरत नहीं है, तो इसे मिटा देना चाहिए. dispose() को कब कॉल करें, इसका सबसे सही तरीका यह है कि नेटिव विज्ञापन से जुड़े AdWidget को विजेट ट्री से हटा दिया जाए और AdListener.onAdFailedToLoad() कॉलबैक से हटा दिया जाए.

अगले चरण

GitHub पर पूरा उदाहरण

नेटिव प्लैटफ़ॉर्म