JNI加载方式分为静态加载与动态加载,这里讲一下静态家在方式。
1.Open Eclipse to create a new Android Application Project.
//add native声明及要加在的本地代码生成的库的名称(xxx.so or xxx.lib)
package com.example.testjni;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//natvie必须声明,用于生成C/C++代码
public native String hello();
static {
System.loadLibrary("testJni");
}
}
2.在工程根目录(/home/xxx/workspace/testJni)执行下面命令:
//javah -classpath /home/xxx/android-sdk-linux/platforms/android-17/android.jar:bin/classes -d jni 包名.类名
javah -classpath /home/xxx/android-sdk-linux/platforms/android-17/android.jar:bin/classes -d jni com.example.testjni.MainActivity
generate header file com_example_testjni_MainActivity.h under /jni directory.
3.create testJniMainActivity.c file implement the function declared in header file
#include <string.h>
#include <jni.h>
jstring JNICALL Java_com_example_testjni_MainActivity_hello
(JNIEnv *env, jobject thiz) {
return (*env)->NewStringUTF(env, "finish jni test!");
}4.create Android.mk file
# 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)
LOCAL_MODULE := testJni
LOCAL_SRC_FILES := testJniMainActivity.c
include $(BUILD_SHARED_LIBRARY)
5.在工程根目录(/home/xxx/workspace/testJni)执行下面命令:
/home/xxx/android-ndk-r10c/ndk-build
[armeabi] Compile thumb : testJni <= testJniMainActivity.c
[armeabi] SharedLibrary : libtestJni.so
[armeabi] Install : libtestJni.so => libs/armeabi/libtestJni.so
我们使用NDK-Build生成的文件是libtestJni.so,我们在使用System.loadLibrary的时候,参数只需要到testJni,而不需要把lib和.so加上
本文详细介绍如何使用JNI进行静态加载,包括创建Android项目、声明本地方法、生成头文件、实现C/C++代码、构建共享库以及在Java代码中调用本地方法。
1397

被折叠的 条评论
为什么被折叠?



