Activity1.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using Android.App;
  3. using Android.Content;
  4. using Android.Runtime;
  5. using Android.Views;
  6. using Android.Widget;
  7. using Android.OS;
  8. using Microsoft.Xna.Framework;
  9. using Android.Gms.Ads;
  10. using Android.Content.PM;
  11. namespace MonoGame.Samples.AdMob
  12. {
  13. [Activity (
  14. Label = "AdMob",
  15. MainLauncher = true,
  16. Icon = "@drawable/icon",
  17. Theme = "@style/Theme.Splash",
  18. ConfigurationChanges=ConfigChanges.Orientation|ConfigChanges.Keyboard|ConfigChanges.KeyboardHidden)]
  19. public class Activity1 : AndroidGameActivity
  20. {
  21. private Game1 _game;
  22. private View _view;
  23. protected override void OnCreate(Bundle bundle)
  24. {
  25. base.OnCreate(bundle);
  26. // Initialize Google Mobile Ads SDK
  27. MobileAds.Initialize(this);
  28. // Create the MonoGame view
  29. _game = new Game1();
  30. _view = _game.Services.GetService(typeof(View)) as View;
  31. // Create a layout to hold both the game and the ad
  32. var layout = new LinearLayout(this)
  33. {
  34. Orientation = Orientation.Vertical
  35. };
  36. // Add the MonoGame view
  37. layout.AddView(_view, new LinearLayout.LayoutParams(
  38. ViewGroup.LayoutParams.MatchParent,
  39. 0, 1f)); // Weight 1 to fill remaining space
  40. // Create and add the AdMob banner
  41. var adView = new AdView(this)
  42. {
  43. AdSize = AdSize.Banner,
  44. AdUnitId = "ca-app-pub-3940256099942544/6300978111" // Test Ad Unit ID
  45. };
  46. var adParams = new LinearLayout.LayoutParams(
  47. ViewGroup.LayoutParams.MatchParent,
  48. ViewGroup.LayoutParams.WrapContent);
  49. layout.AddView(adView, adParams);
  50. // Load an ad
  51. var adRequest = new AdRequest.Builder().Build();
  52. adView.LoadAd(adRequest);
  53. // Set the layout as the content view
  54. SetContentView(layout);
  55. _game.Run();
  56. }
  57. }
  58. }