Writing a Hello-world Android NDK Program

Step 0: Write an Android JNI program

package com.mytest;
 
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
 
public class JNIActivity extends Activity {
 
   static {
      System.loadLibrary("myjni"); // "myjni.dll" in Windows, "libmyjni.so" in Unixes
   } 
   // A native method that returns a Java String to be displayed on the
   // TextView
   public native String getMessage();
 
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);      // Create a TextView.
      TextView textView = new TextView(this);      // Retrieve the text from native method getMessage()
      textView.setText(getMessage());
      setContentView(textView);
   }
}

Step 1: Generating C/C++ Header File using "javah" Utility

> javah --help......// Change directory to <project-root>/jni/include> javah -classpath ../../bin/classes;<ANDROID_SDK_HOME>\platforms\android-<xx>\android.jar 
  -o HelloJNI.h com.mytest.JNIActivity

Step 2: C Implementation - HelloJNI.c

#include <jni.h>
#include "HelloJNI.h"
 
JNIEXPORT jstring JNICALL Java_com_mytest_JNIActivity_getMessage
          (JNIEnv *env, jobject thisObj) {
   return (*env)->NewStringUTF(env, "Hello from native code!");
}

Step 3: Create an Android makefile - Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := myjniLOCAL_SRC_FILES := HelloJNI.cinclude $(BUILD_SHARED_LIBRARY)

Step 4: Build NDK

// Change directory to <project-root>> ndk-buildCompile thumb : myjni <= HelloJNI.c
SharedLibrary  : libmyjni.so
Install        : libmyjni.so => libs/armeabi/libmyjni.so

Step 5: Run the Android App

你可能感兴趣的:(android,NDK,hello-jni)