Android JNI 静态加载

本文详细介绍如何使用JNI进行静态加载,包括创建Android项目、声明本地方法、生成头文件、实现C/C++代码、构建共享库以及在Java代码中调用本地方法。

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加上

6. call hello() function in java code
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值