欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

基于Android studio3.6的JNI教程之helloworld思路详解

时间:2021-05-25 08:22:34|栏目:Android代码|点击:

jdk环境变量配置:

path中增加下面2个路径,也就是android studio的路径,android有自带的jdk。

E:\Android\Android Studio\jre\bin
E:\Android\Android Studio\bin

新建工程:

一定要选择Native c++类型,最后要选c++11支持。

SDK设置:

File->Settings

File->Project Structure

首先确定工程的目录结构,然后尝试运行一下工程,使用模拟器,确保工程没问题,

MainActivity的同级目录,新建一个hello.java,然后做一个简单的实现,

package com.example.myapplication;
 
public class hello {
 public native int add(int i, int j);
}

使用android studio自带的Terminal进入该hello.java所在目录,执行,

javac hello.java

Terminal下回到app/src/main所在目录,执行,

javah -d jni -classpath ./java com.example.myapplication.hello

此时,会在main目录下面生成一个和cpp,java同级的目录jni。

在该目录结构里面新建hello.cpp。

com_example_myapplication_hello.h中的内容复制进hello.cpp中,并且进行方法的实现,

#include <jni.h>
/* Header for class com_example_myapplication_hello */
 
#ifndef _Included_com_example_myapplication_hello
#define _Included_com_example_myapplication_hello
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class: com_example_myapplication_hello
 * Method: add
 * Signature: (II)I
 */
 
#include "com_example_myapplication_hello.h"
 
JNIEXPORT jint JNICALL Java_com_example_myapplication_hello_add
 (JNIEnv *, jobject, jint i, jint j){return i+j;}
 
#ifdef __cplusplus
}
#endif
#endif

com_example_myapplication_hello.h,hello.cpp这连个文件复制到cpp所在的目录,

然后修改CMakeLists.txt,增加,

add_library( # Sets the name of the library.
 hello
 
 # Sets the library as a shared library.
 SHARED
 
 # Provides a relative path to your source file(s).
 hello.cpp )

修改target_link_libraries如下,

target_link_libraries( # Specifies the target library.
  native-lib
  hello
  # Links the target library to the log library
  # included in the NDK.
  ${log-lib} )

修改hello.java的调用方式,

package com.example.myapplication;
 
public class hello {
 
 static {
 System.loadLibrary("hello");
 }
 public native int add(int i, int j);
}

修改MainActivity.java中的onCreate函数,

protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 // Example of a call to a native method
 TextView tv = findViewById(R.id.sample_text);
 //tv.setText(stringFromJNI());
 tv.setText("hello 9+10= " + new hello().add(9, 10));
 }

然后,rebuild project,没有错误后,然后run app

最终程序整体目录结构,以及运行效果,

 JNI的整体流程思路:

Java先定义一个类,类中定义一个需要c++来实现的方法.通过javah生成需要c++实现的.h的c++头文件实现.h的c++头文件中定义的方法Cmake编译运行

总结

上一篇:Android画画板的制作方法

栏    目:Android代码

下一篇:Android编程判断横屏、竖屏及设置横竖屏的方法

本文标题:基于Android studio3.6的JNI教程之helloworld思路详解

本文地址:http://www.codeinn.net/misctech/128554.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有