2

I am developing a chess game for Android, and planning use a AI engine written in C++. So, I have to make a native method call from Java to C++. The sources look like this:

Computer.java

class Computer{
  public native String dumpMethod();
  static{
   System.loadLibrary("mylib");
}

public static String makeMove(){
   return dumpMethod();
}

and c++ file: mylib.cpp

#include <jni.h>
#include <string>

#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL Java_Computer_dumpMethod(JNIEnv *, jobject);
JNIEXPORT void JNICALL Java_Computer_dumpMethod(JNIEnv *env, jobject obj){
  ...
  Engine * engine = new Engine();
  engine->setLevel(10);
  std::string rsult = engine->generateMove();
  ...
  //return result
  ...
}

#ifdef __cplusplus
}
#endif

When I make a call Computer.makeMove() from the main activity, the program crashed without any error information in logcat window. I have no idea about the problem but It seems because the generateMove() execution.

When the level has been set to 10, the generateMove() call takes a long time(up to 15 seconds) to be finished. I think the Android activity just cant wait until it finish and its been crashed.

Everthing works well if the level was set to 1, which means that the generateMove() can be finished and return execution result immediately.

I think I need to make a call in synchronous way but I have no idea about it. Is there any way to make a native call in a synchronous/asynchronous way?

huynq9
  • 522
  • 8
  • 22
  • I saw the same problem posted here: http://stackoverflow.com/questions/11729822/android-jni-native-c-function-call-kills-activity. – huynq9 Sep 19 '14 at 07:26

1 Answers1

0

I am guessing you are calling the JNI Native method: dumpMethod from the main thread, Blocking your main thread for the duration of the execution of your native code. So when you increased to level 10 it took more than the few millisecs/secs it took at level 1 and you got the ANR - Application Not Responding exception.

Try spawning a new thread and calling the native method from the background thread, then when you want to update your UI, send a message to the Main thread message queue.

ZiviMagic
  • 1,034
  • 2
  • 10
  • 25