user976385 user976385 - 12 days ago 5
Android Question

Calling Android native method fail

Recently I am working on the android native method. I found something weird which is I am only allow to define and use the native method at the MainActivity class.

public class MainActivity extends AppCompatActivity {

static {
System.loadLibrary("native-lib");
}

public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
private static final int REQUEST_FINE_LOCATION=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//registerForContextMenu();
stringFromJNIEx();
}

public native String stringFromJNIEx();
.....
}


When I try to call the same method in other class

public class DisplayMessageActivity extends Activity {

static {
System.loadLibrary("native-lib");
}

private MyGLSurfaceView mGLView;

public static String qrCode="";


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
qrCode=message;

mGLView = new MyGLSurfaceView(this);
setContentView(mGLView);

registerForContextMenu(mGLView);

stringFromJNIEx();
}


The apps will throw an exception. Do I miss anything?

Answer

The JNI method signatures are contain the package name and class name. So you can't call the same function from different classes.

Try to create an class for interfacing your native methods. Make them public and static. Like the following snippets.

public class NativeInterface {
    static {
        System.loadLibrary("native-lib");
    }

    public static native void stringFromJNIEx();

}

In the native part your method signature should be like this;

Java_com_package_appname_NativeInterface_stringFromJNIEx