您的位置:首页 > 其它

NDK开发基本流程

2017-01-03 17:17 232 查看
最近在学习NDK的开发,这里把简单的开发流程记录下来

1、新建Android工程

2、在MainActivity中添加一个本地方法:public static native String 方法名(),例如:

public static native String getStringFromC()


3、在项目根目录下建立jni目录

4、在jni目录中通过如下命令添加头文件:javah -classpath bin/classes;android.jar文件路径 -d jni MainActivity文件路径,例如:

javah -classpath bin/classes;D:\sdk\platforms\android-21\android.jar -d jni one.lee.hellondk.MainActivity


5、F5刷新,会出现生成的头文件,在jni目录下建立hello.c文件,编写c文件,方法名从生成的头文件中拷贝过来修改一下即可,这里简单的只输出一条语句,代码如下:

#include <stdio.h>
#include <stdlib.h>
#include "one_lee_hellondk_MainActivity.h"
JNIEXPORT jstring JNICALL Java_one_lee_hellondk_MainActivity_getStringFromC
(JNIEnv * env, jclass jclass){
return (*env)->NewStringUTF(env, "Hello from JNI !");
}


6、在jni目录下建立Android.mk文件,编写mk文件

# Copyright (C) 2009 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0 #
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

#生成的so文件名称
LOCAL_MODULE    := hello
#刚建立的c文件
LOCAL_SRC_FILES := hello.c

include $(BUILD_SHARED_LIBRARY)


7、在项目的根目录下通过执行ndk-build命令生成so文件,F5刷新,此时会在项目根目录下生成libs和obj文件夹,其中含有so文件

8、在MainActivity文件中添加如下代码:

static{
System.loadLibrary("hello");
}


9、MainActivity完整代码如下:

package one.lee.hellondk;

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

public class MainActivity extends Activity {

private TextView mTextView;

static{ System.loadLibrary("hello"); }

public static native String getStringFromC();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text_view);
mTextView.setText(getStringFromC());
}
}


这就是NDK开发的简单的基本流程,希望能给对这方面有理解的兄弟有一些帮助。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ndk jni