Android NDK (HelloJNI)

How will this post help you?

  • You’ll learn how to setup Android studioand use Android NDKand use Native code (C++)in your Android Apps.
  • I will be using Android Studio 2.2 RC

Step 1: Setup Android Studio and Android NDK

Before we can start writing native code we need to download Android NDK using Android SDK Manager as shown in the figure.

Download the Android NDK package and CMake

ndk.pngcmake.png

 

Step 2: Create a new Project in Android studio

Please pay close attention as this is different from other normal android project

  • In this window check the box that says include C++ Support

project_create.png

  • Choose your target Android Devices

create1.png

  • Select the Activity type you want to add

create2.png

  • I’m leaving this to default

create3.png

  • Choose the default toolchain and click Finish

create4.png

Step 3: Run the project

run.png

Screenshot_20160903-194330.png

Step 4: Let’s change the code

  • Open the file native-lib.cpp and add the following code

open.png

  • Java_com_example_aditya_hellondk must match your package
  • Next MainActivity is the name of activity where you’ll use this code
  • stringAnother is the method name
extern "C"
jstring
Java_com_example_aditya_hellondk_MainActivity_stringAnother(JNIEnv *env, jobject) {
    std::string anotherString = "The code is changed now";
    return env->NewStringUTF(anotherString.c_str());
}
  • Now change MainActivity.java as follows
public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

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

        // Example of a call to a native method
        TextView tv = (TextView) findViewById(R.id.sample_text);
        tv.setText(stringAnother());
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
    public native String stringAnother();
}

Step 4: Run it again

You should see this as your output

Screenshot_20160903-202131.png

Conclusion

  • We learned to set up and run a helloJNI project

Github’s link for code

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s