android-----JNI学习 helloworld

(1)新建android工程

android-----JNI学习 helloworld


(2)添加NDK路径

android-----JNI学习 helloworld


(3)添加本地支持

android-----JNI学习 helloworld

给本地库起名

android-----JNI学习 helloworld

此时工程目录下会自动生成jni文件夹

android-----JNI学习 helloworld

此时Makefile也自动生成

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := hello
LOCAL_SRC_FILES := hello.cpp

include $(BUILD_SHARED_LIBRARY)



(4)编写准备生成本地库的 cpp文件

#include <jni.h>
#include <string.h>


 extern "C" {
     JNIEXPORT jstring JNICALL Java_com_snail_helloworld_MainActivity_myhello(JNIEnv * env, jobject obj);
 };

 JNIEXPORT jstring JNICALL Java_com_snail_helloworld_MainActivity_myhello(JNIEnv * env, jobject obj)
 {
	 return env->NewStringUTF("Hello From CPP");
 }


注意

Java_com_snail_hello_MainActivity_myhello

Java                             为固定的

com_snail_helloworld  为包名

MainActivity                 为Activity名称

myhello                        为上层调用的函数名

这几个命名一定要对应,否则上层调用会出现错误:

“java.lang.UnsatisfiedLinkError: Native method not found”

(5)编译本地cpp生成库文件

 在cmd下进入工程目录:

 执行 ndk-build 进行编译(前提是NDK路径已经加入到Path环境变量中)

android-----JNI学习 helloworld

(6)在Activity中调用本地函数库

package com.snail.helloworld;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		TextView myTextField = (TextView)findViewById(R.id.myText);
        myTextField.setText(myhello()); 
	}
	
	public native String myhello();
    
    static {
        System.loadLibrary("hello");
    } 
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}


运行:

android-----JNI学习 helloworld

调用成功!


附录:

ndk-build的选项


所有给ndk-build的选项都会直接传给GNU Make,由make运行NDK的编译脚本。几个常见调用方式如下:

ndk-build 编译

ndk-build clean 清掉二进制文件

ndk-build NDK_DEBUG=1 编译为可调试版的二进制文件

ndk-build NDK_DEBUG=0 编译为release版

ndk-build V=1 执行ndk-build且打印出它所执行的详细编译命令。

ndk-build -B 强制重新编译

ndk-build -B V=1 -B 和 V=1 的组合

ndk-build NDK_LOG=1 打印出内部的NDK日志信息(用于调试NDK自己)

ndk-build NDK_APP_APPLICATION_MK=<文件路径> 用这里指定的路径寻找Application.mk文件

ndk-build -C <project路径> 先cd进入<project路径>,然后执行ndk-build。

(2)官方参考
http://permadi.com/blog/2011/09/creating-your-first-android-jnindk-project-in-eclipse-with-sequoyah/

(3)其他参考

http://cherishlc.iteye.com/blog/1756762