anybody know how to add any other View layer on UnityPlayerAcitivity?

anybody know how to add any other View layer on UnityPlayerAcitivity?
I can use addContentView in eclipse,But when I use it in unity3D,it often forces close.
I don’t know what happened,can anybody help me?
Thanks in advance.

1 Answer

1

That’s because the Unity Player runs in it’s own thread. So if you try to call “addContentView” directly, it will crash because GUI stuff can only be accessed from the thread which created it (basically: The main thread).

You will need to add an method which will call it in the proper thread. Since you call it from the Unity, you should already know how to obtain current activity.

For my AdMob Plugin I added an 2 static classes to show and hide the ads

AdMobBridge.cs:

using UnityEngine;
using System;
using System.Collections;

public class AdMobAndroidBridge : IDisposable {
private AndroidJavaClass cls_TheActivity = new AndroidJavaClass(“com.tseng.MyGame.MyGameActivity”);

public void ShowAds() {
	cls_TheActivity.CallStatic("ShowAds");
}

public void HideAds() {
	cls_TheActivity.CallStatic("HideAds");
}

public void Dispose() {
	if(cls_TheActivity!=null)
		cls_TheActivity.Dispose();
}

}

In Java I have this:

public class MyGameActivity extends UnityPlayerActivity {
	public static void ShowAds() {
		final MyGameActivity currentActivity = (MyGameActivity)UnityPlayer.currentActivity;
		currentActivity.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				currentActivity.showAds();
			}
		});
	}
	public static void HideAds() {
		final MyGameActivity currentActivity = (MyGameActivity)UnityPlayer.currentActivity;
		currentActivity.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				currentActivity.hideAds();
			}
		});
	}

	public void showAds() {
		adView.setVisibility(View.VISIBLE);
		adView.loadAd(adRequest);
		Log.d("AdListener", "showAds");
	}
	
	public void hideAds() {
		adView.setVisibility(View.GONE);
		Log.d("AdListener", "hideAds");
	}
}

with the runOnUiThread was the one which solved the crash problems for me too, because the element which needed to be hided was an UI Element and it can only be modified/accessed from the UI thread.

It’s bit of a mess, but it works.