mk18のアプリ開発日記(cocos2d-x,OpenGL)

2Dゲームアプリのプログラミングついて書きます、Android,iPhone,cocos2d-xとか広告とかの話題が多いです。

Android cocos2d-xにアスタ(アイコン型スマホアプリ広告)の広告を貼る方法

画面上部、GameFeat固定のバナーだと寂しいのでアスタのアイコン型を貼ってみます。

アスタさんのサンプル

activity_main.xmlで定義されたview4つに対して初期化処理をして貼り付けているようです。

package jp.maru.mrdiconsample;


import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

import jp.maru.mrd.IconCell;
import jp.maru.mrd.IconLoader;

public class MainActivity extends Activity {
	
	private IconLoader<Integer> _iconLoader;
	//private static final String _MEDIA_CODE = "__TEST__";
	private static final String _MEDIA_CODE = "ast01070lme5k6ko8aow";
	private final String _LOG_TAG = getClass().getPackage().getName();
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		this.setUpIconLoader();
		this.setUpButtons();
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		_iconLoader.startLoading();  // start loading icon-AD
	}
	
	@Override
	public void onPause()
	{
		_iconLoader.stopLoading(); // stop loading ad
		super.onPause();
	}
	
	protected void setUpIconLoader()
	{
		if (_iconLoader != null) return;
		try {
			// Create instance of IconLoader with mediaCode and Context
			_iconLoader = new IconLoader<Integer>(_MEDIA_CODE, this);
			Log.v(_LOG_TAG, "_iconLoader: "+_iconLoader);
			
			// Retrieve ViewGroup object from content view
			ViewGroup vGrp = (ViewGroup)findViewById(R.id.iconCellLayout1);
			Log.v(_LOG_TAG, "vGrp: "+vGrp);
			
			// Register children of viewGroup into iconLoader
			int i, c = vGrp.getChildCount();
			for (i=0; i<c; i++)
			{
				View view = vGrp.getChildAt(i);
				Log.v(_LOG_TAG, "View at "+i+":"+view);
				if (view instanceof IconCell) {
					((IconCell)view).addToIconLoader(_iconLoader);
				}
			}
			
			_iconLoader.setRefreshInterval(15);
			
		} catch (Exception e) {
			Log.w(_LOG_TAG, "Exception in creation");
			e.printStackTrace();
		}
	}
	
	
	private void setUpButtons()
	{
		Button startButton = (Button)findViewById(R.id.startButton);
		if (startButton != null) {
			startButton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Log.v(_LOG_TAG, " start button was clicked");
					_iconLoader.startLoading();
				}
			});
		}
		Button stopButton = (Button)findViewById(R.id.stopButton);
		if (stopButton != null) {
			stopButton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Log.v(_LOG_TAG, " stop button was clicked");
					_iconLoader.stopLoading();
				}
			});
		}
		Button refreshButton = (Button)findViewById(R.id.refreshButton);
		if (refreshButton != null) {
			refreshButton.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Log.v(_LOG_TAG, " refresh button was clicked");
					_iconLoader.refresh();
				}
			});
		}
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
}

参考サイト

cocos2d-xにアスタを導入してみる:Android

http://gaomar.blog.fc2.com/blog-entry-37.html

【cocos2dx】アスタ広告がAndorid側で表示できない件(解決済み)

http://albatrus.com/main/cocos2d/5046

ここを参考に試して見ましたが、うまく行かずサンプルを使い変形して貼り付けました。

貼り付け方法

アスタさんのサンプルの貼る方法は、xmlファイル経由なのでこのままだとcocos2d-xには貼れません。
cocos2d-xではlayout以下に配置するxmlファイルを使っていないのです。
全部Javaコードでレイアウトを実現しています。
今回もJavaコードで貼る必要があります。
このため、this.getLayoutInflater().inflateを使ってactivity_mainを変数に代入した後
FrameLayout経由でaddContentView()しています。
activity_main.xmlは今回用に修正してあります。
それとアプリの文字をsetTitleColor()で白に変更しました。

//アスタ
		m_view = this.getLayoutInflater().inflate(R.layout.activity_main, null);
		final FrameLayout.LayoutParams adParams3 = new FrameLayout.LayoutParams(WC,WC);
		adParams3.gravity = (Gravity.TOP|Gravity.CENTER); 
		addContentView(m_view, adParams3);
		//setContentView(view);
		this.setUpIconLoader();

ソースコード

/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package com.terasurware.hapihomu;

import java.util.HashMap;

import jp.basicinc.gamefeat.android.sdk.controller.GameFeatAppController;
import jp.basicinc.gamefeat.android.sdk.controller.GameFeatIconAdLoader;
import jp.basicinc.gamefeat.android.sdk.view.GameFeatBannerView;
import jp.basicinc.gamefeat.android.sdk.view.GameFeatIconView;
import jp.maru.mrd.IconCell;
import jp.maru.mrd.IconLoader;

import net.nend.android.NendAdListener;
import net.nend.android.NendAdView;

import org.cocos2dx.lib.Cocos2dxActivity;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.analytics.tracking.android.Tracker;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

/***
【apiKey】
156acedaf3da1f622b7353afd794f7a2c7790a19 
【spotID】
100470 
 */

public class SimpleGame extends Cocos2dxActivity implements NendAdListener{
	static final String TAG ="SimpleGame";
	private final int WC = LinearLayout.LayoutParams.WRAP_CONTENT; 
	private final int MP = LinearLayout.LayoutParams.MATCH_PARENT;
	Tracker m_tracker;
	
	private int m_nend_counter;

    // ジャストのサイズにする
    private final int FP = LinearLayout.LayoutParams.FILL_PARENT;
    // 広告レイアウト
    private LinearLayout iconAdView; 
    // アイコン型広告
    private static final String _MEDIA_CODE = "ast01070lme5k6ko8aow"; //←メモした識別コードに変えてください
    private IconLoader<Integer> iconAd;
    private View m_view = null; 
    
	private IconLoader<Integer> _iconLoader;
	//private static final String _MEDIA_CODE = "__TEST__";
	private final String _LOG_TAG = getClass().getPackage().getName();
    
	GameFeatIconAdLoader myIconAdLoader;
	int m_count, m_game_feat_flag;
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		
		Log.v(TAG, "onCreate");
		
		Global.activity = this;
		m_count = 0;
		m_game_feat_flag = 0;
		m_nend_counter = 0;
		
		//nend
		final NendAdView nendAdView = new NendAdView(getApplicationContext(), 
				100470, "156acedaf3da1f622b7353afd794f7a2c7790a19");	//本番のID
		final FrameLayout.LayoutParams adParams = new FrameLayout.LayoutParams(WC,WC);
		adParams.gravity = (Gravity.BOTTOM|Gravity.CENTER); 
		//addContentView(nendAdView, adParams);
        nendAdView.loadAd();
        nendAdView.setListener(this);
        
        //GameFeat Android オファーウォール呼び出し型 素材
        final GameFeatBannerView banner = new GameFeatBannerView(SimpleGame.this);
		final FrameLayout.LayoutParams adParams2 = new FrameLayout.LayoutParams(WC,WC);
		adParams2.gravity = (Gravity.TOP|Gravity.CENTER); 
        //addContentView(banner, adParams2);
		
		//アスタ
		m_view = this.getLayoutInflater().inflate(R.layout.activity_main, null);
		final FrameLayout.LayoutParams adParams3 = new FrameLayout.LayoutParams(WC,WC);
		adParams3.gravity = (Gravity.TOP|Gravity.CENTER); 
		addContentView(m_view, adParams3);
		//setContentView(view);
		this.setUpIconLoader();
		
		//m_view.setVisibility(View.VISIBLE);
		//m_view.setVisibility(View.INVISIBLE);
		
		int n;
		n = getEventNum();
		send_gga("event_num",n);
		//n = getCollectNum();
		//send_gga("collect_num",n);
		
		//あとから広告を表示する
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
        		Log.v(TAG, "postDelayed");
        		addContentView(nendAdView, adParams);
                //addContentView(banner, adParams2);
        		//m_view.setVisibility(View.VISIBLE);
        		/***
        		addContentView(view, adParams3);
        		setUpIconLoader();
        		_iconLoader.startLoading();  // start loading icon-AD
        		***/

            }
        }, 5000); 
        
		Log.v(TAG, "onCreate end");
	}
	

	protected void setUpIconLoader()
	{
		if (_iconLoader != null) return;
		try {
			// Create instance of IconLoader with mediaCode and Context
			_iconLoader = new IconLoader<Integer>(_MEDIA_CODE, this);
			Log.v(_LOG_TAG, "_iconLoader: "+_iconLoader);
			
			// Retrieve ViewGroup object from content view
			ViewGroup vGrp = (ViewGroup)findViewById(R.id.iconCellLayout1);
			Log.v(_LOG_TAG, "vGrp: "+vGrp);
			
			// Register children of viewGroup into iconLoader
			int i, c = vGrp.getChildCount();
			for (i=0; i<c; i++)
			{
				View view = vGrp.getChildAt(i);
				Log.v(_LOG_TAG, "View at "+i+":"+view);
				if (view instanceof IconCell) {
					((IconCell)view).addToIconLoader(_iconLoader);
					((IconCell)view).setTitleColor(0xffffffff);
				}
			}
			
			_iconLoader.setRefreshInterval(15);
			
		} catch (Exception e) {
			Log.w(_LOG_TAG, "Exception in creation");
			e.printStackTrace();
		}
	}

	
	/**
	     * アイコン型広告初期化
	     */
	private void initIconAd()
	{
		Log.v(TAG, "initIconAd");
		
		iconAdView = new LinearLayout(this);
		RelativeLayout.LayoutParams layoutParams = 
				new RelativeLayout.LayoutParams(FP, (int)(80 * getResources().getDisplayMetrics().density));
		// 中央揃え
		iconAdView.setGravity(Gravity.CENTER_HORIZONTAL);
		iconAdView.setLayoutParams(layoutParams);

		// アイコン型広告識別コード設定
		iconAd = new IconLoader<Integer>(_MEDIA_CODE, this);
		// 更新インターバル15秒
		iconAd.setRefreshInterval(15);

		// 今回は4つのアイコンを設置します
		for (int ii=0; ii<4; ii++) {
			final LinearLayout iconAdSubView = new LinearLayout(SimpleGame.this);
			LinearLayout.LayoutParams layoutSubParams = new LinearLayout.LayoutParams(1, (int)(80 * getResources().getDisplayMetrics().density), 1.0f);
			iconAdSubView.setLayoutParams(layoutSubParams);
			// ここでIconAd.javaを呼び出します
			new IconAd(SimpleGame.this, iconAdSubView, iconAd);
			// 設定したアイコンデータをViewに追加する
			iconAdView.addView(iconAdSubView);
		}
	}
		
    public void showGameFeat(){
		Log.v(TAG, "showGameFeat");
		
		if(m_nend_counter>0){
			GameFeatAppController.setPopupProbability(1);
			GameFeatAppController.showPopupAd(SimpleGame.this);
			m_count = 0;
			m_count++;
			m_game_feat_flag = 1;
    	} else {
            nativeEnd();
    		this.finish();
    	}
    }
    
    //アナリティクスへ送信
    public void send_gga(String lavel, int val){
        Log.v(TAG, "send_gga " + lavel + " " + val);
    	
    	EasyTracker easyTracker = EasyTracker.getInstance(this);

    	easyTracker.send(MapBuilder
    			.createEvent("game",	// Event category (required)
    					"save_data",  	// Event action (required)
    					lavel,   			// Event label
    					(long) val)       	// Event value
    					.build()
    		);
    }
    //
	
    @Override
    protected void onStart() {
        Log.v(TAG, "onStart");
        super.onStart();
        EasyTracker.getInstance(this).activityStart(this);  // Add this method.
    }

	public static native void nativeEnd();
	
    @Override
    protected void onResume() {
        super.onResume();
		_iconLoader.startLoading();  // start loading icon-AD
		
        Log.v(TAG, "onResume");
		m_count++;
        Log.v(TAG, "m_count = " + m_count);
        
        /***
        if(m_count>=2){
            Log.v(TAG, "onResume finish");
            nativeEnd();
        	this.finish();
        }
        ***/
        
        if( m_game_feat_flag==1){
            Log.v(TAG, "onResume finish");
            nativeEnd();
        	this.finish();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        Log.v(TAG, "onRestart");
    }
    
    @Override
    public void onPause(){
		_iconLoader.stopLoading(); // stop loading ad
    	super.onPause();
		Log.v(TAG, "onPause");
    }
    
    @Override
    protected void onStop() {
        Log.v(TAG, "onStop");
        super.onStop();
        EasyTracker.getInstance(this).activityStop(this);  // Add this method.
    }

    @Override
    protected void onDestroy() {
        Log.v(TAG, "onDestroy");

        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.v(TAG, "onActivityResult " + resultCode);
    }
    
    //nend
    /** 受信エラー通知 */
    public void onFailedToReceiveAd(NendAdView nendAdView) {
        Log.v(TAG, "nend onFailedToReceiveAd");
    }
    /** 受信成功通知 */
      public void onReceiveAd(NendAdView nendAdView) {
    	  m_nend_counter++;
          Log.v(TAG, "nend onReceiveAd " + m_nend_counter);
    }
    /** クリック通知 */
      public void onClick(NendAdView nendAdView) {
          Log.v(TAG, "nend onClick");
    }
    /** 復帰通知 */
      public void onDismissScreen(NendAdView nendAdView) {
          Log.v(TAG, "nend onDismissScreen");
    }

      //putで作る
      public void putEventNum(int n){
    	  Log.v(TAG, "saveEventNum " + n);
        	SharedPreferences pref = getPreferences(MODE_PRIVATE);
          	Editor e = pref.edit();
          	e.putInt("com.terasurware.hapihomu.event_num", n);	//put
          	e.commit();
      }
      public int getEventNum(){
    	  SharedPreferences pref =getPreferences(MODE_PRIVATE);
    	  int flag = pref.getInt("com.terasurware.hapihomu.event_num", 0);
    	  Log.v(TAG, "get_EventNum " + flag ); 
    	  return flag;
      }

      //putで作る
      public void putCollectNum(int n){
    	  Log.v(TAG, "saveCollectNum " + n);
    	  SharedPreferences pref = getPreferences(MODE_PRIVATE);
    	  Editor e = pref.edit();
    	  e.putInt("com.terasurware.hapihomu.collect_num", n);	//put
    	  e.commit();
      }
      public int getCollectNum(){
    	  SharedPreferences pref =getPreferences(MODE_PRIVATE);
    	  int flag = pref.getInt("com.terasurware.hapihomu.collect_num", 0);
    	  Log.v(TAG, "get_EventNum " + flag ); 
    	  return flag;
      }
	
      static {
        System.loadLibrary("game");
      }
      
      //
      /**
       * uuidを保存
       */
      private void put_uuid(String uuid){
          Log.v(TAG, "put_uuid " + uuid ); 
      	SharedPreferences pref = getPreferences(MODE_PRIVATE);
      	Editor e = pref.edit();
      	e.putString("com.terasurware.hapihomu.uuid", uuid);	//put
      	e.commit();
      }
      
      /**
       * uuidを取得する
       */
      private String get_uuid(){
      SharedPreferences pref =getPreferences(MODE_PRIVATE);
      	String str = pref.getString("com.terasurware.hapihomu.uuid", null);	//get
      	if(str==null){
      		Log.v(TAG, "get_uuid null"); 
      	} else {
      		Log.v(TAG, "get_uuid " + str ); 
      	}
      	return str;
      }

      //
}

/***
//GameFeat アイコン型 コードから貼り付け、成功していない
LinearLayout l = new LinearLayout(this);
myIconAdLoader = new GameFeatIconAdLoader();

GameFeatIconView i1 = new GameFeatIconView(this);
GameFeatIconView i2 = new GameFeatIconView(this);
GameFeatIconView i3 = new GameFeatIconView(this);

l.addView(i1);
l.addView(i2);
l.addView(i3);

i1.addLoader(myIconAdLoader);
i2.addLoader(myIconAdLoader);
i3.addLoader(myIconAdLoader);

//addContentView(l, adParams);
 ***/

レイアウトファイル

不要な物をコメントアウトし、class="jp.maru.mrd.IconCell" のviewを残しました。
RelativeLayoutを残さないとうまくいかないです。
iconCellLayout1以下のレイアウトではうまく行かなくてRelativeLayoutからとしました。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <!--
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />
    -->

    <!-- controls -->

    <!--
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/startButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/start" />

        <Button
            android:id="@+id/refreshButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/refresh" />

        <Button
            android:id="@+id/stopButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/stop" />
    </LinearLayout>
    -->
    
    <!-- setting id iconCellLayout1 -->

    <LinearLayout
        android:id="@+id/iconCellLayout1"
        android:layout_width="fill_parent"
        android:layout_height="80dp"
        android:layout_alignParentTop="true"
        android:background="#00ffff66"
        android:gravity="center"
        android:orientation="horizontal" >

        <view
            android:layout_width="1dp"
            android:layout_height="80dp"
            android:layout_weight="1"
            class="jp.maru.mrd.IconCell"
            android:background="#00ffcccc" />

        <view
            android:layout_width="1dp"
            android:layout_height="80dp"
            android:layout_weight="1"
            class="jp.maru.mrd.IconCell"
            android:background="#00ccffcc" />

        <view
            android:layout_width="1dp"
            android:layout_height="80dp"
            android:layout_weight="1"
            class="jp.maru.mrd.IconCell"
            android:background="#009999ff" />

        <view
            android:layout_width="1dp"
            android:layout_height="80dp"
            android:layout_weight="1"
            class="jp.maru.mrd.IconCell"
            android:background="#00ffccff" />
        <!--  -->
    </LinearLayout>

</RelativeLayout>

スクリーンショット

文字も白くなっていい感じです。
f:id:mk18:20131030111437p:plain

作ってるアプリ

『はぴホム!~ 探索錬金アドベンチャー ~』
http://terasur.blog.fc2.com/blog-entry-544.html