简体   繁体   中英

Getting AndroidJavaException in Unity when trying to call class constructor

I am using this C# code in Unity to access Java classes is .aar lib:

 AndroidJavaClass ajc;
    private AndroidJavaObject ajo;
    // Use this for initialization
    void Start () {
        ajc = new AndroidJavaClass("com.example.pc.superpoweredsdk.SuperPoweredPlayerWrapper");
        ajo = ajc.Get<AndroidJavaObject>("currentActivity");
    }

but I am getting this error in logcat on android:

AndroidJavaException: java.lang.NoSuchFieldError: no "Ljava/lang/Object;" field "currentActivity" in class "Lcom/example/pc/superpoweredsdk/SuperPoweredPlayerWrapper;" or its superclasses 07-01 12:31:08.640 1467 1485 I Unity : java.lang.NoSuchFieldError: no "Ljava/lang/Object;" field "currentActivity" in class "Lcom/example/pc/superpoweredsdk/SuperPoweredPlayerWrapper;" or its superclasses

this is Java class and functions I am trying to call:

public class SuperPoweredPlayerWrapper {
    public SuperPoweredPlayerWrapper(Context context) {
        int sampleRate = 44100;
        int bufferSize = 512;
        AssetFileDescriptor fd = context.getResources().openRawResourceFd(R.raw.lycka);
        int fileOffset = (int)fd.getStartOffset();
        int fileLength = (int)fd.getLength();
        try {
            fd.getParcelFileDescriptor().close();
        } catch (IOException e) {
            android.util.Log.d("", "Close error.");
        }
        SuperpoweredPlayer(sampleRate, bufferSize, context.getPackageResourcePath(), fileOffset, fileLength);
    }

    private native void SuperpoweredPlayer(int sampleRate, int bufferSize, String apkPath, int fileOffset, int fileLength);
    public native void playPause(boolean play);
    public native void setTempo(double value);

    static {
        System.loadLibrary("SuperpoweredExample");
    }
}

How to call this class constructor with context parameter from Unity?

currentActivity is a member of com.unity3d.player.UnityPlayer.

So, this code will get the context

AndroidJavaClass ajc;
AndroidJavaObject ajo,context;
ajc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        ajo = ajc.Get<AndroidJavaObject>("currentActivity");
context = ajo.Call<AndroidJavaObject>("getApplicationContext");

then you do whatever you want with the context.

Calling the constructor:

AndroidJavaObject yourClassObject = new AndroidJavaObject("com.example.pc.superpoweredsdk.SuperPoweredPlayerWrapper",new object[]{context});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM