我在Unity中使用这个C#代码来访问Java类是.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");
}
但我在android上的logcat中收到此错误:
AndroidJavaException:java.lang.NoSuchFieldError:no&#34; Ljava / lang / Object;&#34; field&#34; currentActivity&#34;在课堂&#34; Lcom / example / pc / superpoweredsdk / SuperPoweredPlayerWrapper;&#34;或者它的超类 07-01 12:31:08.640 1467 1485 I Unity:java.lang.NoSuchFieldError:no&#34; Ljava / lang / Object;&#34; field&#34; currentActivity&#34;在课堂&#34; Lcom / example / pc / superpoweredsdk / SuperPoweredPlayerWrapper;&#34;或其超类
这是我试图调用的Java类和函数:
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");
}
}
如何使用Unity中的context参数调用此类构造函数?
答案 0 :(得分:1)
currentActivity 是 com.unity3d.player.UnityPlayer的成员。
因此,此代码将获取上下文
AndroidJavaClass ajc;
AndroidJavaObject ajo,context;
ajc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
ajo = ajc.Get<AndroidJavaObject>("currentActivity");
context = ajo.Call<AndroidJavaObject>("getApplicationContext");
然后你用上下文做任何你想做的事。
调用构造函数:
AndroidJavaObject yourClassObject = new AndroidJavaObject("com.example.pc.superpoweredsdk.SuperPoweredPlayerWrapper",new object[]{context});