Calling c program from different Android project

87 views Asked by At

I am using Android Studio version - 2.1.2. I have created one project in Android - MyNdk. This project uses c program. The c progarm has a function getCountry(). This function is created in the file torento.c. Function is like this -

Java_com_myndk_MainActivity_getCountry(JNIEnv *env, jobject instance) **{**

   // TODO
   //return (*env)->NewStringUTF(env, returnValue);

   return (*env)->NewStringUTF(env, "Canada");

**}**

In the java file, I have used this code to load the library, System.loadLibrary("torento"). libtorento.so is created successfully under jni folder for all devices. So far no problem, I can call the c program with out any error.

Now I have created second project - HelloAndroidJni. This project also uses c program. I want to use the getCountry() from libtorento.so. This project has the c program paris.c, which is created under jni folder. For this project the library is libparis.so. Now I have created a folder jniLibs, under which I have copied libtorento.so from the first project for all device. Then I have loaded the libraries using the following code in java file.

static
{
    System.loadLibrary("torento");
    System.loadLibrary("paris");

}

libtorento.so is loaded successfully in HelloAndroidJni project. I have checked .apk file. libtorento.so exists in the .apk file.

My question is how will I call the getCountry() in the HelloAndroidJni project . I have searched lot, everywhere tutorial/sample is given where c program is called from the same java project, where it is defined. Please help me.

In Android Studio( 2.1.2), system generated jni folder and c file. No header file is created.

2

There are 2 answers

0
Alex Cohn On

In the second project, you should create a new Java class com.myndk.MainActivity (I know t is not in the same Java package as the main activity for the new project). You can copy the MainActivity.java file from the myNdk project, or simply create a new one. The only requirement is that that class has defined the native method get country().

Now you can use this method in your new app.

5
User365 On

following your instruction, I have made this in HelloAndroidJni. Have I done right ? My class is as follows

package com.dsc.bandhan.helloandroidjni;

@SuppressWarnings("JniMissingFunction") public class MainActivity extends AppCompatActivity {

TextView txtName;


static
{
    System.loadLibrary("torento");
    System.loadLibrary("paris");

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    txtName=(TextView)findViewById(R.id.txtName);

    txtName.setText(getCountry());


}


public native String getCountry();

}

It is not working. It shows the following error java.lang.UnsatisfiedLinkError: Native method not found: com.dsc.bandhan.helloandroidjni.MainActivity.getCountry:()Ljava/lang/String;