디지털 노마드/안드로이드 앱 만들기

안드로이드 스튜디오 애드몹 설정하기

LEO Kim 2019. 9. 12. 23:00
반응형

안드로이드 스튜디오 애드몹 설정하기

 

안녕하세요. 안드로이드 스튜디오로 어플을 개발하는데 초보자들이 많이 힘들어 하는 부분들이 있는것 같아요.

저도 아직 초보인데 그래서 고생을 많이 했답니다.

그래서 저도 기록할겸 초보도 쉽게 할 수있도록 적으려고합니다.

 

우선 안드로이드 스튜디오에서 애드몹 설정하는것이 정말 어려운데요.

이해가 안되는 부분이 많거든요.

특히 안드로이드 스튜디오가 버전업을 하면서 애드몹 설정이 구글에 나와있는것과 차이가 난답니다.

또한, 애드몹은 인앱을 통한 수익이 아닌경우 필수적으로 설정을 하는 거라서 꼭 필요한데요.

 

순서대로 따라 오시면됩니다.

1. 파이어베이스 설정하기.

파이어베이스는 안드로이드 스튜디오를 통해서 애드몹 뿐만이 아니라 다른 구글 서비스를 이용하는데 많은 도움을 주기 때문에 꼭 가입해서 연동하기를 추천합니다.

파이어 베이스 설정하는 것은 나중에 링크로 올릴께요.

 

2. 안드로이드 스튜디오 애드몹 설정

안드로이드 스튜디오에서 만든 앱과 파이어베이스를 연동했으면 이제 애드몹을 설정해볼께요.

 

복사만 해도 충분히 설정이 된답니다. 

a. strings.xml

<!-- 테스트용-->

   <string name="APPLICATION_ID">ca-app-pub-3940256099942544~3347511713</string>

   <string name="banner_ad_unit_id">ca-app-pub-3940256099942544/6300978111</string>

   <string name="Interstitial_ad_unit_id">ca-app-pub-3940256099942544/1033173712</string>

 

테스트용으로 우선 해두는 것이 매우 중요합니다.

애드몹에서 실제 아이디를 사용하면 엄청 문제가 커깁니다. 짤릴수 있어요...

 

b. Build.gradle (app 수준)

dependencies{

implementation'com.google.firebase:firebase-ads:17.2.0'

}

 추가 하시고 sync를 꼭 눌러주세요.

 

c. MyApplication.java

import android.app.Application;

public class MyApplication extends Application {

    public static String Interstitial_ad_unit_id;

    public static String APPLICATION_ID;

    @Override

    public void onCreate(){

        super.onCreate();

        //테스트용

        MyApplication.Interstitial_ad_unit_id = "ca-app-pub-3940256099942544/1033173712";

        MyApplication.APPLICATION_ID = "ca-app-pub-3940256099942544~3347511713";

    }

}

 

MyApplication.java 파일은 따로 만들어서 해주시면됩니다.

테스트용으로 따로 만들어 둔건 실제 사용용으로 쉽게 바꾸기 위해서예요.

 

d. Intro (empty activity를 만들기)

이건 전면광고를 사용하기 위한 코드인데요.

보통 인트로를 사용하시는 경우가 많아서 이렇게 인트로를 최초 실행 엑티비티로 만들었습니다.

메인엑티비티에 넣어도 됩니다.

   i. Intro.java

import android.os.Bundle;

import android.app.Activity;

import android.content.Intent;

import android.os.Handler;

import com.google.android.gms.ads.MobileAds;

public class Intro extends Activity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_intro); //xml , java 소스 연결

        //전면광고 start

        String APPLICATIONID = MyApplication.APPLICATION_ID;

        MobileAds.initialize(this, APPLICATIONID);

        //전면광고 end

        Handler handler = new Handler();

        handler.postDelayed(new Runnable(){

            @Override

            public void run() {

                Intent intent = new Intent (getApplicationContext(), MainActivity.class);

                startActivity(intent); //다음화면으로 넘어감

                finish();

            }

        },3000); //3 뒤에 Runner객체 실행하도록

    }

    @Override

    protected void onPause(){

        super.onPause();

        finish();

    }

}

 

ii. Intro.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <ImageView

        android:id="@+id/introImage"

        android:layout_width="0dp"

        android:layout_height="match_parent"

        android:layout_weight="1"

        android:scaleType="fitXY"

        android:src="@drawable/intro"

        app:srcCompat="@drawable/intro"

        tools:srcCompat="@drawable/intro"

        tools:ignore="ContentDescription"/>

</LinearLayout>

 

e. 메니페스토 파일 수정

intent-filter intro 옮긴 어플리케이션 시작전에 넣기

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 

아래의 코드는 application  안에 넣으면 됩니다.

<!--SampleAdMobAppID:ca-app-pub-3940256099942544~3347511713-->

<meta-data

android:name="com.google.android.gms.ads.APPLICATION_ID"

android:value="@string/APPLICATION_ID"/>

 

 

f.  MainActivity.java 수정 (광고 넣을 부분을 수정합니다. / 배너광고 전면광고 포함했습니다.)

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

 

//광고로드

import com.google.android.gms.ads.AdListener;

import com.google.android.gms.ads.AdRequest;

 

//배너광고

import com.google.android.gms.ads.AdView;

 

//전면광고

import com.google.android.gms.ads.InterstitialAd;

 

public class MainActivity extends AppCompatActivity {

 

    //배너광고

    private AdView mAdView;

 

    //전면광고

    private InterstitialAd mInterstitialAd;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        //배너광고

        mAdView = findViewById(R.id.adView);

        AdRequest adRequest = new AdRequest.Builder().build();

        mAdView.loadAd(adRequest);

 

        //전면광고

        String Interstitial_id = MyApplication.Interstitial_ad_unit_id;

 

        mInterstitialAd = new InterstitialAd(this);

        mInterstitialAd.setAdUnitId(Interstitial_id);

        mInterstitialAd.loadAd(new AdRequest.Builder().build());

 

    }

 

    @Override

    public void onBackPressed() {

        // 혹시 뷰를 사용하는 액티비티일 경우 웹뷰 뒤로가기를 구현해준다.

          /*   if (webView.canGoBack()) {

                 webView.goBack();

             } else { */

        if (mInterstitialAd.isLoaded()) {

            mInterstitialAd.show();

            mInterstitialAd.setAdListener(new AdListener() {

                @Override

                public void onAdClosed() {

                    // 사용자가 광고를 닫으면 뒤로가기 이벤트를 발생시킨다.

                    finish();

                }

            });

        } else {

            super.onBackPressed();

        }

    }

}

 

 

g.  Activity_main.xml 수정(배너부분 넣는것)

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:ads="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity"

    android:orientation="vertical">

 

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="0dp"

        android:layout_weight="9">

        <TextView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="Hello World!" />

    </LinearLayout>

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="0dp"

        android:layout_weight="1">

        <com.google.android.gms.ads.AdView

            android:id="@+id/adView"

            android:layout_width="match_parent"

            android:layout_height="match_parent"

            android:layout_gravity="center"

            ads:adSize="BANNER"

            ads:adUnitId="@string/banner_ad_unit_id">

        </com.google.android.gms.ads.AdView>

 

    </LinearLayout>

 

</LinearLayout>

 

안드로이드 스튜디오처럼 복사하는 방법을 몰라서 우선 이렇게 적었습니다.

저도 그대로 복사해서 사용하고 있어요 ㅋㅋㅋㅋ

다음에는 파이어베이스를 통해서 메세지 보내는거 코드 넣을께요.

반응형