Hey guys,
I am working along the same lines but I am having loads of problems making it work.I am using a java plugin in my project and trying to call it with the help of JNI.I am not getting any errors,but the app is not opening in the Experia.I have attached my code snippet.The function I am calling from java takes no arguments and returns an integer.Plzzzzz help.
My bridge,
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System;
public class CallJavaCode : MonoBehaviour {
private IntPtr JavaClass;
private int getFlag;
void Start ()
{
// attach our thread to the java vm; obviously the main thread is already attached but this is good practice…
JavaVM.AttachCurrentThread();
// first we try to find our main activity…
IntPtr cls_Activity = JNI.FindClass(“com/unity3d/player/UnityPlayer”);
int fid_Activity = JNI.GetStaticFieldID(cls_Activity, “currentActivity”, “Landroid/app/Activity;”);
IntPtr obj_Activity = JNI.GetStaticObjectField(cls_Activity, fid_Activity);
Debug.Log("obj_Activity = " + obj_Activity);
// create a JavaClass object…
IntPtr cls_JavaClass = JNI.FindClass(“org/example/ScriptBridge/JavaClass”);
int mid_JavaClass = JNI.GetMethodID(cls_JavaClass, “”, “(Landroid/app/Activity;)V”);
IntPtr obj_JavaClass = JNI.NewObject(cls_JavaClass, mid_JavaClass, obj_Activity);
Debug.Log("JavaClass object = " + obj_JavaClass);
// create a global reference to the JavaClass object and fetch method id(s)…
JavaClass = JNI.NewGlobalRef(obj_JavaClass);
getFlag = JNI.GetMethodID(cls_JavaClass, “getFlag”, (Ljava/lang/void;)Ljava/lang/int;);
int flagId=JNI.GetFieldID(cls_JavaClass, “flag”, “()Ljava/lang/int;”);
Debug.Log("JavaClass global ref = " + JavaClass);
Debug.Log("JavaClass method id = " + getFlag);
}
private string cacheDir = “view my car”;
void OnGUI ()
{
if (GUI.Button(new Rect (15, 125, 450, 100), cacheDir))
{
Debug.Log("getFlag calling ");
int cache=getMyFlag();
cacheDir=“My flag is”+cache;
Debug.Log("getCacheDir returned ");
}
}
private int getMyFlag()
{
// again, make sure the thread is attached…
JavaVM.AttachCurrentThread();
// get the Java String object from the JavaClass object
int myFlag= JNI.CallIntMethod(JavaClass,getFlag);
Debug.Log(“Step 1”);
// convert the Java String into a Mono string
// IntPtr stringPtr = JNI.GetStringUTFChars(str_cacheDir, 0);
Debug.Log(“Step 2”);
// String cache = Marshal.PtrToStringAnsi(stringPtr);
//JNI.ReleaseStringUTFChars(str_cacheDir, stringPtr);
Debug.Log(“Step 3”);
return myFlag;
}
}
My java class,
package org.example.ScriptBridge;
import android.app.Activity;
public class JavaClass
{
static int f = 5;
private Activity mActivity;
public JavaClass(Activity currentActivity)
{
mActivity = currentActivity;
}
public void setFlag()
{
f++;
}
public int getFlag()
{ //int cacheDir = mActivity.getMyFlag();
return f;
}
}
Plzzzzzzzzzzzzzzzzz help!!!
My error is coming in:
JavaVM.AttachCurrentThread();