深入浅析jni中的java接口使用

所属分类: 软件编程 / java 阅读数: 147
收藏 0 赞 0 分享

JNI中的java接口使用

项目需求,需要在c++函数中监听相应的状态,并在java端进行一些列的处理。

这个需要在JNI中写一个subscriber,注册后在需要的地方进行引入使用。

目录结构

初始化是AS上的c++工程文件,这边先暂时实现简单的demo,CdemoActivity是NativeActivity的实现,我们暂时别管,因为实现是c++层控制的,有兴趣可以去百度下

主要涉及jnicallback等c文件和JNIUtil这java文件

JNIUtil

public class JNIUtil {

  static {

    System.loadLibrary("native-event");
  }

  // 注册函数
  public static native void setJniCallBack(JniCallBack callBack);

  // 解注册函数
  public static native void unJniCallBack();

  public interface JniCallBack{

    void onReceiveCInfo();

  }

}

jnicallback.h

//
// Created by 86130 on 2020/9/9.
//

#ifndef CDEMO_JNICALLBACK_H
#define CDEMO_JNICALLBACK_H


#ifdef __cplusplus
extern "C"{
#endif

//方法回调
void onReceiveMsg();


#ifdef __cplusplus
}
#endif
#endif //CDEMO_JNICALLBACK_H

jnicallback.cpp

#include <jni.h>
#include <malloc.h>
#include <cstring>

#include "jnicallback.h"

#ifdef __cplusplus
extern "C"{
#endif

  JavaVM *g_VM;
  jobject subscriber;

extern "C"
JNIEXPORT void JNICALL Java_com_demo_cdemo_JNIUtil_setJniCallBack(JNIEnv* env,jclass clazz, jobject call_back) {

  env->GetJavaVM(&g_VM);
  subscriber = env->NewGlobalRef(call_back);

}

extern "C"
JNIEXPORT void JNICALL Java_com_demo_cdemo_JNIUtil_unJniCallBack(JNIEnv* env, jclass clazz) {

  if (subscriber != NULL)
  {
    env->DeleteGlobalRef(subscriber);
  }
}

JNIEnv *getEnv()
{
  JNIEnv *env;
  if (g_VM ==NULL)
  {
    return NULL;
  }
  int envStat = g_VM->GetEnv((void **) &env, JNI_VERSION_1_6);
  if (envStat == JNI_EDETACHED)
  {
    if (g_VM->AttachCurrentThread(&env, NULL) != 0)
    {
      return NULL;
    }
  }
  return env;
}

jmethodID getMethodIdByNameAndSig(JNIEnv *env, const char *name, const char *sig)
{
  if (env == NULL || subscriber == NULL)
  {
    return NULL;
  }
  jclass subscriberClass = env->GetObjectClass(subscriber);
  if (subscriber == 0)
  {
    return NULL;
  }
  jmethodID methodId = env->GetMethodID(subscriberClass, name, sig);
  if (methodId == 0)
  {
    return NULL;
  }
  return methodId;
}

// 头文件方法实现
void onReceiveMsg()
{
  JNIEnv *env = getEnv();
  jmethodID onReceiveMethodId = getMethodIdByNameAndSig(env, "onReceiveCInfo", "()V");
  if (onReceiveMethodId == NULL)
  {
    return;
  }
  env->CallVoidMethod(subscriber, onReceiveMethodId);

}

#ifdef __cplusplus
}
#endif

在其他的cpp文件中引入jnicallback的头文件就可以使用相应的方法。

CMake文件

project(Native-Activity)

cmake_minimum_required(VERSION 3.4.1)

#引入native_app_glue头文件
include_directories(F:/AndroidSdk/Sdk/ndk-bundle/sources/android/native_app_glue)

add_library(native-activity SHARED
    main.cpp
     jnicallback.cpp)

add_library(native-event SHARED jnicallback.cpp)

find_library(log-lib log)
find_library(OPENGLES3_LIBRARY GLESv3 "OpenGL ES v3.0 library")
find_library(EGL_LIBRARY EGL "EGL 1.4 library")
find_library(android-lib android)

#编译为静态库
add_library(app_glue STATIC
    android_native_app_glue.c)

target_link_libraries(native-event
    ${log-lib} #链接log库
    ${android-lib} #链接android库
    )

target_link_libraries(native-activity
    app_glue #链接静态库native_app_glue
    ${log-lib} #链接log库
    ${android-lib} #链接android库
    ${OPENGLES3_LIBRARY} #链接OpenGLES库
    ${EGL_LIBRARY} #链接EGL库
    )

JNIUtil的使用

package com.demo.cdemo;

import android.app.NativeActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
public class CdemoActivity extends NativeActivity {

  static {
    System.loadLibrary("native-activity");
  }

  boolean isFirst = false;

  @Override 
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    JNIUtil.setJniCallBack(new JNIUtil.JniCallBack() {
      @Override
      public void onReceiveCInfo() {
        boolean isMain = isMainThread();
        Log.d("zzkk",
            "CdemoActivity onReceiveCInfo isMain = " + isMain);
        if (!isFirst)
        {
          isFirst = true;
          runOnUiThread(new Runnable() {
            @Override public void run() {
              Intent intent = new Intent(CdemoActivity.this
                  , MainActivity.class);
              startActivity(intent);
            }
          });
        }
      }
    });

  }

  private boolean isMainThread() {
    return Looper.getMainLooper() == Looper.myLooper();
  }

}

可以看见onReceiveCInfo这行日志的打印

综上

更多精彩内容其他人还在看

详解Spring依赖注入:@Autowired,@Resource和@Inject区别与实现原理

这篇文章主要介绍了详解Spring依赖注入:@Autowired,@Resource和@Inject区别与实现原理,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

了解spring中的CloudNetflix Hystrix弹性客户端

这篇文章主要介绍了了解spring中的CloudNetflix Hystrix弹性客户端,客户端弹性模式是在远程服务发生错误或表现不佳时保护远程资源(另一个微服务调用或者数据库查询)免于崩溃。,需要的朋友可以参考下
收藏 0 赞 0 分享

Spark学习笔记Spark Streaming的使用

这篇文章主要介绍了Spark学习笔记Spark Streaming的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

通过实例讲解springboot整合WebSocket

这篇文章主要介绍了通过实例讲解springboot整合WebSocket,WebSocket为游览器和服务器提供了双工异步通信的功能,即游览器可以向服务器发送消息,服务器也可以向游览器发送消息。,需要的朋友可以参考下
收藏 0 赞 0 分享

java虚拟机学习笔记进阶篇

在本篇内容里小编给大家分享了关于java虚拟机学习笔记的进阶内容,需要的朋友们跟着学习下。
收藏 0 赞 0 分享

java虚拟机学习高级篇

在本篇文章里小编给大家整理了关于java虚拟机学习高级篇的相关内容,有兴趣的朋友们跟着学习参考下。
收藏 0 赞 0 分享

java虚拟机中多线程总结

在本篇内容中小编给大家分享的是关于java虚拟机中多线程的知识点总结内容,需要的朋友们参考学习下。
收藏 0 赞 0 分享

java虚拟机多线程进阶篇总结

在本篇内容里小编给大家整理了关于java虚拟机多线程进阶篇的相关知识点内容,有兴趣的朋友们跟着参考下。
收藏 0 赞 0 分享

java数据结构和算法中数组的简单入门

在本文里小编给大家整理了关于java数据结构和算法中数组的简单入门知识点整理,需要的朋友们学习下。
收藏 0 赞 0 分享

java数据结构和算法中哈希表知识点详解

在本篇文章里小编给大家分享了关于java数据结构和算法中哈希表的相关知识点内容,需要的朋友们学习下。
收藏 0 赞 0 分享
查看更多