Thursday, May 7, 2015

Android Studio Native Programming

I am trying to take the difficulty out of using Android Studio for creating native applications.

Create Android Studio Project


1. Launch Android Studio and Start a new Android Studio Project


2. Enter a name for the application ("My Native App") and a domain ("example.com") and make sure the Project Location is in a place that makes sense.


3. Choose the devices the app will run on. (Use default)


3. Add an activity. (Use default)



4. Customize Activity (Use default) Simply click Finish.


Your screen should now look like this:


Create Native Method


1. Find app->java->com.example.mynativeapp->MainActivity and add "public native String getStringFromNative();" (highlighted in the right panel) as the last method of class MainActivity:



Find local properties and add your path to the ndk directory as shown below (change C\:\\dev.. to your own local path):


Open up the terminal tab and change the directory to "app\src\main":


Next we need to create the java header file for the native method. I always create a batch file to do this, as it is easily editable and can be reused in modified form for other projects. I name it "createheader.bat" and looks like this:
javah -d .\jni -classpath C:\dev\Android\sdk1\extras\android\support\v7\appcompat\libs\android-support-v4.jar;C:\dev\Android\sdk1\extras\android\support\v7\appcompat\libs\android-support-v7-appcompat.jar;C:\dev\Android\sdk1\platforms\android-21\android.jar;..\..\build\intermediates\classes\debug com.example.mynativeapp.MainActivity

I put all the paths that you need to adjust to your own install locations in red bold.
This creates the native header file in a "jni" folder next to the "main" folder inside "src".

Now we want to copy the just generated file into our implementation file named "main.c".
Do this by highlighting "com_example_mynativeapp_MainActivity.h" in the project view and pressing the F5 key. It should come up with a copy prompt where you change the "com_example_mynaticeapp_MainActivity.h" file name to "main.c":

Now change the include near the top to:
#include "com_example_mynativeapp_MainActivity.h"
and delete everything except for the getStringFromNative prototype near the bottom of the file.
I also added an implementation of the native function. Look closely at the screenshot below:

Before you can compile, you need to generate another empty .c file. You can just press F5 to copy the main.c file. I named it "util.c" and then wiped it blank. Gradle currently just needs this file to compile successfully. They may fix this at some point: