Android docking SDK encountered problems and solutions

#### In the interaction between Unity and Android, you can use the AndroidJavaProxy class to interact

 

First define the interface in android, implement this interface in Unity, and inherit from AndroidJavaProxy. Then it can be called in the form of polymorphism in android. After calling, it will call the code of C#, and then we can realize the callback we want with Unity and Android.

 

example:

In Android define

```java

public interface RewardAdListener {

    public void onReward(String str);

}

```

 

Implement this interface in Unity

```csharp

public sealed class RewardAdListener : AndroidJavaProxy

{

    public RewardAdListener() : base("com.adSdk.AdTest0916.RewardAdListener")

    {

    }

    public void onReward(string str)

    {

        Debug.Log("Unity: "+str);

    }

}

```

 

The method open to Unity in Android

```java

 public void LoadAwardAd(RewardAdListener listener) {

     listener.onReward("Distribute Reward");

 }

```

 

Unity calls the method of Android

```csharp

    AndroidJavaObject jo = new AndroidJavaObject("com.adSdk.AdTest0916.RewardAd");

    adNative.Call("LoadAwardAd",  new RewardAdListener());

```

 

That's it, but there is still a problem that the Java callback is in the sub-thread. When the sub-thread calls the method of the main thread, an error will be reported, so the method needs to be executed in the main thread.

 

```csharp

    AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");

    AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");

 

    AndroidJavaObject jo = new AndroidJavaObject("com.adSdk.AdTest0916.RewardAd"); // This jo needs to use the previously obtained RewardAd class, otherwise it is newly created

 

     var runnable = new AndroidJavaRunnable(() =>

        {

            Debug.Log("execute show");

            jo.Call("ShowRewardAd", activity);

        });

        activity.Call("runOnUiThread", runnable);

```

 

https://blog.csdn.net/sgnyyy/article/details/53048552

https://docs.unity3d.com/ScriptReference/AndroidJavaRunnable.html

 

Guess you like

Origin blog.csdn.net/weixin_41292299/article/details/114977479