So I created a plugin that shows ads in the Unity game. From Unity, I want to call methods in the class that extends UnityPlayerActivity. Here is some of my code from com/mycompany/mygame/MainActivity.java
:
public class MainActivity extends UnityPlayerActivity {
private static AdView adView;
// Code the initializes the ad view goes here
...
public static void hideAd() {
adView.setVisibility(View.INVISIBLE);
}
public static void showAd() {
adView.setVisibility(View.VISIBLE);
}
}
hideAd()
and showAd()
are the methods I would like to be able to call from Unity. In Unity, here is some example code I have to test my plugin:
AndroidJavaClass ajc;
bool ohBool = true;
void Update () {
foreach (Touch touch in Input.touches) {
if (touch.phase == TouchPhase.Began) {
// Call my function
float touchLoc = Camera.main.ScreenToWorldPoint(touch.position).y;
if (touchLoc > 0.0f) {
if (showAd) {
ajc.CallStatic("hideAd");
showAd = false;
}
else {
ajc.CallStatic("showAd");
showAd = true;
}
}
}
}
}
However, LogCat spits this at me whenever these function calls happen:
AndroidJavaException: android.view.ViewRootImpl$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy can touch its views.
What can I do about this?
Edit: Here is my init code as asked for:
void Start() {
AndroidJNI.AttachCurrentThread();
ajc = new AndroidJavaClass("com.mycompany.mygame.MainActivity");
}