您的位置:首页 > 移动开发

第一个NDK程序 MyFirstNDK_app

2015-12-09 11:06 495 查看
       本文分享自己第一个NDK APP程序的开发全过程,前提是Android SDK 和 NDK 已经正确地安装和配置。

       如何安装Android SDK , 参考:http://jingyan.baidu.com/article/d621e8da0999062865913f3b.html

       如何安装 NDK , 参考:http://jingyan.baidu.com/article/3ea51489e7a9bd52e61bbac7.html

       我使用NDK r10e版本,不同版本的NDK,使用JNI的方法有所不同。

       (1)下面开始新建一个android工程:



    取名随意,我取名为:MyFirstNDK_app。请注意设置 minSDK , targetSDK , 不可大意。

    (2)直接右键选中项目MyFirstNDK_app,新建一个 jni 文件夹



(3)编写 android.mk , application.mk 和 hello-jni.c , 完全自己新建有点麻烦,可以先导入ndk解压目录下面的samples\Hello-Jni项目,然后直接复制过来:



       到了这一步,尤其需要注意两个问题:

       1. 如果存在cpp文件,如下图

   


       HelloJni.cpp的文件名是我们自己项目的名称,注意修改;

       2. hello-jni.c 中函数名的意义:Java_包名_调用native方法的类名_native方法名,比如,我的函数名是:

                Java_com_example_myfirstndk_MainActivity_stringFromJNI

  (4)编写 MainActivity.java

package com.example.myfirstndk_app;

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

public class MainActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

/* Create a TextView and set its content.
* the text is retrieved by calling a native
* function.
*/
TextView  tv = new TextView(this);
tv.setText( stringFromJNI() );
setContentView(tv);
}

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

/* This is another native method declaration that is *not*
* implemented by 'hello-jni'. This is simply to show that
* you can declare as many native methods in your Java code
* as you want, their implementation is searched in the
* currently loaded native libraries only the first time
* you call them.
*
* Trying to call this function will result in a
* java.lang.UnsatisfiedLinkError exception !
*/
public native String  unimplementedStringFromJNI();

/* this is used to load the 'hello-jni' library on application
* startup. The library has already been unpacked into
* /data/data/com.example.hellojni/lib/libhello-jni.so at
* installation time by the package manager.
*/
static {
System.loadLibrary("hello-jni");
}
}


  (5) 配置NDK的编译选项

        有好几种配置的方法,具体参考:http://www.cnblogs.com/skyseraph/p/3979238.html

        我采用的是第二种,不需要cygwin , 关键步骤截图如下:


      具体的配置:



         (6)右键点击项目 -> Android tools -> Add native support



     (7)右键点击项目->run as android application ,大功告成 !



 PS:有可能在编译过程中出现类似于 jnienv could not be resolved 的错误

    解决方法:

    是由于没有将jni.h导入的缘故,而这个文件在ndk的目录下面。所以,参照以下步骤:

Project Properties -> C/C++ General -> Path and Symbols

选择include标签,Add -> $Android_NDK_HOME/platforms/android-18/arch-arm/usr/include

其中,android-18是我自己采用的4.3的版本号,即target-version,这个因人而异。

且选中All languages.

最后Apply -> OK

这样错误就解决了。

   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android NDK