1

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");
}
danglingPointer
  • 882
  • 8
  • 32
  • You may want to post the code for how you are initializing `adView` and `ajc` – ozbek May 20 '14 at 01:00
  • You can find an answer here: http://stackoverflow.com/questions/13746940/android-calling-ui-thread-from-worker-thread ... Any view related manipulations must be done on the UI thread. In your case you should call `runOnUiThread` (with runnables that actually hide or show your ad view) from within your `hideAd` and `showAd` methods. On second sight... those methods are static so you need to resort to posting on the UI thread using the ad view if it is already set. – tiguchi May 20 '14 at 01:03

1 Answers1

2

Try attach current thread first.

void Start() {
    AndroidJNI.AttachCurrentThread();
    AndroidJavaClass ajc = new AndroidJavaClass("com.mycompany.mygame.MainActivity"); //This is your java class hierarchy
    ajc.CallStatic("showAd");
}
Verv
  • 763
  • 6
  • 9
  • Hmm.. It seems nothing wrong in unity, maybe the error is in your AndroidManifest or java function. – Verv May 22 '14 at 02:03