How will this post help you?

You’ll learn how to setup Android studio and use Android NDK and use Native code (C++) in your Android Apps.

and use and use 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

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

Choose your target Android Devices

Select the Activity type you want to add

I’m leaving this to default

Choose the default toolchain and click Finish

Step 3: Run the project

Step 4: Let’s change the code

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

Java_com_example_aditya_hellondk must match your package

must match your package Next MainActivity is the name of activity where you’ll use this code

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

Conclusion

We learned to set up and run a helloJNI project

Github’s link for code