JNI初步(五)jni ndk 一個.so檔案依賴另一個.so檔案的寫法

2020-10-10 14:00:39

jin 的步驟首先參考https://blog.csdn.net/we1less/article/details/108930467

注意:本文是在ndk環境下編寫

1.寫native類宣告native方法

package com.godv.audiosuc;

public class NativePlayers {
    static{
        System.loadLibrary("JNI_ANDROID_AUDIOS");
        System.loadLibrary("JNI_ANDROID_TEST");
    }
    //native方法
    public static native int show(String url);
    public static native String shutDown();
}

2.java-h 生成對應的jni 標頭檔案

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_godv_audiosuc_NativePlayers */

#ifndef _Included_com_godv_audiosuc_NativePlayers
#define _Included_com_godv_audiosuc_NativePlayers
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_godv_audiosuc_NativePlayers
 * Method:    show
 * Signature: (Ljava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_com_godv_audiosuc_NativePlayers_show
  (JNIEnv *, jclass, jstring);

/*
 * Class:     com_godv_audiosuc_NativePlayers
 * Method:    shutDown
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_godv_audiosuc_NativePlayers_shutDown
  (JNIEnv *, jclass);

#ifdef __cplusplus
}
#endif
#endif

3.寫實現類呼叫另一個cpp中的方法 (這裡稱這個類為  方法類

#include "NativePlayers.h"
#include <stdio.h>
#include <stdlib.h>
#include "Test.h"

JNIEXPORT jint JNICALL Java_com_godv_audiosuc_NativePlayers_show
        (JNIEnv * env, jclass clazz, jstring jstr)
{
    Test t;
    return t.play();
}

JNIEXPORT jstring JNICALL Java_com_godv_audiosuc_NativePlayers_shutDown
        (JNIEnv * env, jclass clazz)
{
    jstring str = env->NewStringUTF("Im godv !");
    return str;
}

3.1.方法類c++

#ifndef FFMPEG_TEST_H
#define FFMPEG_TEST_H

#include <stdio.h>
#include <stdlib.h>

class Test{
public:
    int play();
};


#endif //FFMPEG_TEST_H
#include "Test.h"

int Test::play() {
    return 0;
}

4.首先將方法類封裝成.so動態庫

4.1android.mk檔案

LOCAL_PATH := $(call my-dir)    
 
include $(CLEAR_VARS)            
LOCAL_MODULE := JNI_ANDROID_TEST
LOCAL_SRC_FILES := Test.cpp    
include $(BUILD_SHARED_LIBRARY) 

 4.2ndk-build 生成 libJNI_ANDROID_TEST.so

5.寫生成jni .so檔案   android.mk檔案

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE    := libJNI_ANDROID_TEST
LOCAL_SRC_FILES := libJNI_ANDROID_TEST.so
include $(PREBUILT_SHARED_LIBRARY)

#LOCAL_ALLOW_UNDEFINED_SYMBOLS := true

include $(CLEAR_VARS)

LOCAL_MODULE := JNI_ANDROID_AUDIOS

LOCAL_SRC_FILES := NativePlayers.cpp

LOCAL_LDLIBS += -L$(SYSROOT)/usr/lib -llog

LOCAL_SHARED_LIBRARIES := libJNI_ANDROID_TEST \

include $(BUILD_SHARED_LIBRARY)

7.呼叫完畢