我的NDK开发之旅 No.1 环境搭建

来源:互联网 发布:吉林麻将源码 编辑:程序博客网 时间:2024/06/11 11:48

这里使用的是Eclipse juno 和ndk 10rd。 主要参考文章为  https://mhandroid.wordpress.com/2011/01/23/using-eclipse-for-android-cc-development/, 在此之上稍加改动。


注意:
随ndk包一起下载的docs中有若干html文件,但是Getting Started with NDK 中讲述的过程是完全不正确的(最起码在我电脑上有各种问题)。


Eclipse上设置NDK路径的文章哪里都有。在此略过不提。


1. 建立一个简单的Android project, MyAdroidProject, 所有设置默认即可。

2. project目录下建立一个jni文件夹。在此文件夹下面创建文件 native.c , 内容如下:


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

/* This is a trivial JNI example where we use a native method
 * to return a new VM String. See the corresponding Java source
 * file located at:
 *
 *   apps/samples/hello-jni/project/src/com/example/hellojni/HelloJni.java
 */
 jstring  Java_com_example_myandroidproject_MainActivity_stringFromJNI( JNIEnv* env,
                                                  jobject thiz )
{

    return (*env)->NewStringUTF(env, "Hello from JNI !");
}

注意上面的函数签名,是package name +类名称+自定义的函数名称


然后在同样的地方创建Android.mk文件,内容如下:


LOCAL_PATH := $(call my-dir)
 
include $(CLEAR_VARS)
 
LOCAL_LDLIBS    := -llog
 
LOCAL_MODULE    := native
LOCAL_SRC_FILES := native.c
 
include $(BUILD_SHARED_LIBRARY)


注意上面的文件名,需要和源代码的文件名相同

原文中说道作者遇到了很多语法错误,但是我这里没有遇到,仅仅告诉我NewStringUTF找不到引用。搜索许久找不到答案,只能按照某文章的说法,去掉Method can not be resolved 语法检查。具体位置在 project->properties->c/c++ general->code analysis->config,去掉勾选就可以了。

MainActivity的内容主要是从layout获取一个TextView,然后设置成JNI中获取的字符串:

package com.example.myandroidproject;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ((TextView)findViewById(R.id.test)).setText(stringFromJNI());
    }


    @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;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public  native String stringFromJNI();
    static {
        System.loadLibrary("native");
    }
}



然后右键,run as android application。 完成!




0 0
原创粉丝点击