본문 바로가기
Etc

adMob - banner, libgdx

by ses jeon 2019. 11. 23.

Try connecting the admob ad to libgdx. Get the blog libgdx example.

The basic method of connecting Android and ios is introduced on the libgdx wiki. If you are new to reading, please read the following article.

libgdx에 애드몹 광고 연결을 해봅니다. 동 블로그 libgdx 예제를 가져옵니다.

 

안드로이드와 ios와의 연결을 하는 기본 방법은 libgdx wiki에 소개되어 있습니다. 혹시 처음 보신다면 다음 글을 읽어보시길 바랍니다.

https://github.com/libgdx/libgdx/wiki/Interfacing-with-platform-specific-code

 

libgdx/libgdx

Desktop/Android/HTML5/iOS Java game development framework - libgdx/libgdx

github.com

In summary, we will create an interface on the core and implements it on a class that works on both core and android, and pass it as a parameter of new MyGdxGame (the class, ...) at the first creation.

1. Banner Advertising
Add google ad service to build.gradle. Version may vary.

내용을 요약하면 core쪽에 interface를 만들어서 core와 android에서 같이 동작하는 클래스에 implements 시키고, 첫 생성시에 new MyGdxGame( 해당 클래스, ... ) 의 매개변수로 전달하는것입니다.

 

1. 배너 광고

build.gradle에 구글 ad service를 추가합니다. 버전은 다를수 있습니다.

1
  api 'com.google.android.gms:play-services-ads:17.1.1'
cs

Also add the following to your android manifest:

또 안드로이드 manifest에 다음을 추가합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<manifest>
...
    <uses-permission android:name="android.permission.INTERNET"/>
...    
    <application>
...
        <activity>
...
 
        </activity>
....
 
        <meta-data
                android:name="com.google.android.gms.ads.APPLICATION_ID"
                android:value="ca-app-pub- Your code "/>
    </application>
</manifest>
cs

You will need to be connected to the Internet, and you can put the code id you received from Google admob in the meta-data.
The following modifies AndroidLauncher. Editing will allow the banner to be inserted and removed at the desired timing.
Theoretical coding referred to the following:

인터넷 연결이 되야될것이고, meta-data에는 구글 admob에서 받은 code id를 넣어주면 됩니다.

다음은 AndroidLauncher를 수정합니다. 수정은 배너를 원하는 타이밍에 넣고 뺄수 있게 하겠습니다.

이론적인 코딩은 다음을 참고했습니다.

https://github.com/libgdx/libgdx/wiki/Admob-in-libgdx

 

libgdx/libgdx

Desktop/Android/HTML5/iOS Java game development framework - libgdx/libgdx

github.com

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
        MyGdxGame mainScreen;
        AdView adView;
 
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
 
        MobileAds.initialize(this"ca-app-pub- Your id");
        
        mainScreen = new MyGdxGame();
        
        RelativeLayout layout = new RelativeLayout(this);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        layout.setLayoutParams(params);
 
        View gameView=initializeForView(mainScreen, config);
 
        RelativeLayout.LayoutParams gameViewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        gameViewParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        gameViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
 
        gameView.setLayoutParams(gameViewParams);
        layout.addView(gameView);
 
        adView = new AdView(this);
        adView.setAdSize(AdSize.BANNER);
        adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111"); //google banner test id
 
        AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
        adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
        adView.loadAd(adRequestBuilder.build());
 
        RelativeLayout.LayoutParams topParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        topParams.addRule(RelativeLayout.ALIGN_PARENT_TOP,RelativeLayout.TRUE);
        topParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        layout.addView(adView, topParams);
        adView.setBackgroundColor(android.graphics.Color.TRANSPARENT);
 
        setContentView(layout);
    }
cs

Initialize the admob at line9.

And the key is to create a view of the layout as initializeForView instead of the existing initialize (new MyGdxGame ()). Then put the adView in the desired location, top or bottom. Here I put it on the top.

Next we will create a switch to turn the banner on and off.

line9 에서 애드몹을 초기화시킵니다.

 

그리고 기존의 initialize(new MyGdxGame()) 대신에 initializeForView로써 layout의 하나의 View를 만들어주는것이 핵심입니다. 그리고 adView를 원하는 위치, 상단이나 하단에 넣어줍니다. 여기서는 상단에 넣고 있습니다.

 

다음으로 배너를 켜고 끌수 있는 스위치를 만들겠습니다.

1
2
3
public interface BannerService {
    void showAds(boolean show);
}
cs

 

Create an interface in core.

Banner adview
adView.setVisibility (View.VISIBLE);
adView.setVisibility (View.GONE);
You can turn it on and off this way. Since adView is a variable of androidLauncher, androidLauncher immediately implements BannerService to handle showAds ().

core에 인터페이스를 하나 만듭니다.

 

배너는 adView를

adView.setVisibility(View.VISIBLE);

adView.setVisibility(View.GONE);

이런 식으로 켜고 끌수 있습니다. adView가 androidLauncher의 변수이므로, androidLauncher가 BannerService를 바로 implements해서 showAds()를 처리하게 하겠습니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class AndroidLauncher extends AndroidApplication implements BannerService {
 
...
 
    private final int SHOW_ADS = 1;
    private final int HIDE_ADS = 0;
 
    protected Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what) {
                case SHOW_ADS:
                {
                    adView.setVisibility(View.VISIBLE);
                    break;
                }
                case HIDE_ADS:
                {
                    adView.setVisibility(View.GONE);
                    break;
                }
            }
        }
    };
 
    @Override
    public void showAds(boolean show) {
        handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
    }
    @Override
    protected void onPause() {
        super.onPause();
        adView.pause();
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        adView.resume();
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        adView.destroy();
    }
...
 
 
}
 
cs

 

Now androidLauncher itself is the class that handles the BannerService. We will pass the launcher itself to the core as a parameter. Modify the core MyGdxGame constructor.

자 그러면 androidLauncher 자체가 BannerService를 처리하는 클래스입니다. 런처 자체를 core에 파라메타로 넘기도록 하겠습니다. core의 MyGdxGame의 constructor를 수정합니다.

It's not a good idea, but I've assigned it to a GLOBAL variable for faster processing. It would be nice to convert global variables to singleton objects. Then change AndroidLauncher as well.

좋은 방법은 아니지만 빠르게 처리하기 위해서 GLOBAL변수에 할당했습니다. 글로벌 변수는 싱글톤 객체로 바꾸는것이 좋을 것입니다. 그러면 AndroidLauncher도 같이 바꾸어주면 됩니다.

And you can turn the banner on and off at the desired timing in core.

The source has a configuration that goes from the loading screen to the main page.
We will turn off the banner on the loading screen and turn it on on the main page.

그리고 core에서 원하는 타이밍에 배너를 켜고 끄면 될것 같습니다.

 

해당 소스는 로딩화면에서 메인페이지로 넘어가는 구성을 가지고 있습니다.

로딩화면에서는 배너를 끄고, 메인페이지에서는 켜겠습니다.

loading
mainPage
loading
mainPage

댓글