随笔 - 65  文章 - 0  评论 - 21  阅读 - 32万

【学习Android NDK开发】native code通过JNI调用Java方法

1、建立Android应用

application name: CallJavaMethod

package name: com.example.cjm

main Activity: MainActivity

main Activity layout: activity_main

 

2、Java实现

打开layout/activity_main.xml布局文件,添加按钮控件,ID为“display_button_activity_main”

复制代码
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/display_button_activity_main"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Display"
        tools:context=".MainActivity" />

</RelativeLayout>
复制代码

 

新建接口CJMListener,定义接口方法displaymessage

package com.example.cjm;

public interface CJMListener {
    void displayMessage(String message);
}

 

新建类CJM,实现接口CJMListener

定义native public方法displaySomething

复制代码
package com.example.cjm;

import android.os.Handler;

public class CJM implements CJMListener {
    
    static {
        System.loadLibrary("cjm");
    }
    
    private Handler handler;
    private CJMListener listener;
    
    public CJM(CJMListener listener) {
        handler = new Handler();
        this.listener = listener;
    }

    @Override
    public void displayMessage(final String message) {
        handler.post(new Runnable() {

            @Override
            public void run() {
                listener.displayMessage(message);
            }
        });
    }
    
    public native void displaySomething();

}
复制代码

 

为MainActivity类,实现CJMListener,添加CMJ对象域

添加Button对象域,引用在布局文件中定义ID为“display_button_activity_main”的按钮控件

复制代码
package com.example.cjm;

import android.os.Handler;

public class CJM implements CJMListener {
    
    static {
        System.loadLibrary("cjm");
    }
    
    private Handler handler;
    private CJMListener listener;
    
    public CJM(CJMListener listener) {
        handler = new Handler();
        this.listener = listener;
    }

    @Override
    public void displayMessage(final String message) {
        handler.post(new Runnable() {

            @Override
            public void run() {
                listener.displayMessage(message);
            }
        });
    }
    
    public native void displaySomething();

}
复制代码

 

当用户按下按钮,执行CJM对象的displaySomething方法

类CJM的displaySomething方法使用native关键字进行声明,将使用native code实现

实现上,在nativie code中,会回调CJM对象的displayerMessage方法,并传递String类型的消息,用于显示

注意,在CJM类中displayerMessage的实现,由于native code并不是在主线程中执行,所以使用了Android的Handler执行MainActivity的方法

 

3、C实现

使用javah为CJM的native方法生成头文件(步骤省略……)

新建.c文件,实现该头文件的方法

复制代码
#include "com_example_cjm_CJM.h"

JNIEXPORT void JNICALL Java_com_example_cjm_CJM_displaySomething
  (JNIEnv *env, jobject thiz) {

    jclass ClassCJM = (*env)->FindClass(env, "com/example/cjm/CJM");
    jmethodID MethodDisplayMessage = (*env)->GetMethodID(env, ClassCJM, "displayMessage", "(Ljava/lang/String;)V");
    jstring value = (*env)->NewStringUTF(env, "Hello World!");
    (*env)->CallVoidMethod(env, thiz, MethodDisplayMessage, value);

}
复制代码

 

JNI调用Java方法的步骤:

1) 获取jmethodID;

GetMethodID

jmethodID GetMethodID(JNIEnv *env, jclass clazz,
const char *name, const char *sig);

Returns the method ID for an instance (nonstatic) method of a class or interface. The method may be defined in one of the clazz’s superclasses and inherited by clazz. The method is determined by its name and signature.

GetMethodID() causes an uninitialized class to be initialized.

To obtain the method ID of a constructor, supply <init> as the method name and void (V) as the return type.

2) 调用Java方法;

NativeType Call<type>Method(JNIEnv *env, jobject obj,
jmethodID methodID, ...);

Methods from these three families of operations are used to call a Java instance method from a native method.They only differ in their mechanism for passing parameters to the methods that they call.

These families of operations invoke an instance (nonstatic) method on a Java object, according to the specified method ID. The methodID argument must be obtained by calling GetMethodID().

When these functions are used to call private methods and constructors, the method ID must be derived from the real class of obj, not from one of its superclasses.

Instance Method Calling Routines:

CallVoidMethod void
CallObjectMethod jobject
CallBooleanMethod jboolean
CallByteMethod jbyte
CallCharMethod jchar
CallShortMethod jshort
CallIntMethod jint
CallLongMethod jlong
CallFloatMethod jfloat
CallDoubleMethod jdouble

 

 

运行结果截图:

 

 

posted on   Anthony Li  阅读(7850)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
< 2012年10月 >
30 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31 1 2 3
4 5 6 7 8 9 10

博客园博客已停止更新,博客地址:dyinigbleed.com

点击右上角即可分享
微信分享提示