iT邦幫忙

DAY 20
1

Android 探索之備忘錄系列 第 20

Android 探索之備忘錄 [Day20-AndroidNDK-2]

  • 分享至 

  • xImage
  •  

使用NDK往往都會include其他的library

從NDK的sample code也可以看到一個two-libs的範例

使用上也是很簡單

Java檔先把library載入並呼叫C function:

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

TextView tv = new TextView(this);
int x = 1000;
int y = 42;

System.loadLibrary("twolib-second");

int z = add(x, y);

tv.setText( "The sum of " + x + " and " + y + " is " + z );
setContentView(tv);
}
public native int add(int x, int y);

撰寫兩個C 檔

//first.c
#include "first.h"
int  first(int  x, int  y)
{
    return x + y;
}

//second.c
#include "first.h"
#include <jni.h>
jint
Java_com_example_twolibs_TwoLibs_add( JNIEnv*  env,
                                      jobject  this,
                                      jint     x,
                                      jint     y )
{
    return first(x, y);
}

最後是JNI的Android.mk

LOCAL_PATH:= $(call my-dir)

# first lib, which will be built statically
#
include $(CLEAR_VARS)

LOCAL_MODULE    := libtwolib-first
LOCAL_SRC_FILES := first.c

include $(BUILD_STATIC_LIBRARY)

# second lib, which will depend on and include the first one
#
include $(CLEAR_VARS)

LOCAL_MODULE    := libtwolib-second
LOCAL_SRC_FILES := second.c

LOCAL_STATIC_LIBRARIES := libtwolib-first

include $(BUILD_SHARED_LIBRARY)

再參照Android-NDK-1篇進行編譯後, 就可以實現APP使用JNI載入其他native libary的功能囉!

運行畫面如下:


上一篇
Android 探索之備忘錄 [Day19-Suspend]
下一篇
Android 探索之備忘錄 [Day21-Foreground Service]
系列文
Android 探索之備忘錄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言