文档章节

在android studio中创建Hello-JNI工程

nextowang
 nextowang
发布于 2016/07/23 16:33
字数 1352
阅读 128
收藏 0
点赞 0
评论 0

1. Overview

What you'll need :

  • Android Studio 2.2 or higher from formal release or canary[version before 2.0 also fine].
  • Android NDK version 11c+.
  • Latest Android SDK tools.
  • A test device with a USB cable or Emulator with Android 5.0+.

2. Create Java Sample App

  1. Find and start Android Studio on your development system:
    a) Linux: Run studio.sh from your installed location
    b) OSX: Find studio installation in Application folder, double click to start
    If this is the first time you run this version of Android Studio on this system, Android Studio will prompt to import from previous settings, just select "I do not have a previous version of Studio or I do not want to import my settings", "Welcome to Android Studio" will be displayed.
  2. Select "Start a new Android Studio project".
  3. On "New Project" page, change "Application Name" to HelloAndroidJni, and leave the default values for other fields.
  4. Click "Next", select "Basic Activity" as our template in "Add an Activity to Mobile" page
  5. Click "Next" all the way to "Finish" to complete application creation.
    This creates an Android "Hello World" Java app; your Android Studio looks like:
  6. (Optional) Connect your Android Device with USB cable if you have device available; otherwise, create an Emulator when Android Studio prompts you in the next step.
  7. Sync , Build and Run , you will see the following on your target device or Emulator:
  8. Configure the project to use gradle wrapper.
    a) On Mac OS, menu "Android Studio" > "Preferences".
    b) On Linux, menu "File" > "Settings".
    c) Then "Build, Execution, Deployment" > "Build Tools" > "Gradle".
    d) Select "Use Default Gradle wrapper (recommended)", click "OK".
  9. Configure Android Studio to download NDK
    a) Menu "Tools" > "Android" > "SDK Manager"
    b) Select tab "SDK Tools"
    c) Check "Android NDK"[ or "NDK"] if it is not checked
  10. Sync , Build and Run , you should see the same as in step 6.

3. Add JNI Build Capability to HelloAndroidJni Project

Android Studio supports native development via experimental plugin developed by Google, let's add it into our project.

  1. Find the latest gradle-experimental plugin version[currently is 0.7.2 at the writing]. Open project build.gradle in Android Studio's "Project" window.
  2. Replace gradle plugin
classpath 'com.android.tools.build:gradle:2.1.0'

with your latest version[it does not have to be 0.7.2]:

classpath 'com.android.tools.build:gradle-experimental:0.7.2'
  1. Change to the latest gradle version (2.10 is required for plugin version 0.7.0).
    Select Android Studio "Project" pane, "Gradle Scripts" > "gradle-wrapper.properties (Gradle Version)" and change:
    distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip
    to:
    distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
  2. Convert the auto-generated module build.gradle to Gradle's component model DSL.
    Select Android Studio "Project" pane > "Gradle Scripts" > "build.gradle (Module: app)" and replace:
apply plugin: 'com.android.application'

android {
   compileSdkVersion 23
   buildToolsVersion "23.0.1"

   defaultConfig {
       applicationId "com.google.sample.helloandroidjni"
       minSdkVersion 22
       targetSdkVersion 23
       versionCode 1
       versionName "1.0"
   }
   buildTypes {
       release {
           minifyEnabled false
           proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
       }
   }
}
// others below this line: no change

with:

apply plugin: 'com.android.model.application'

model {
   android {
       compileSdkVersion = 23
       buildToolsVersion = "23.0.3"

       defaultConfig {
           applicationId = "com.google.sample.helloandroidjni"
           minSdkVersion.apiLevel = 22
           targetSdkVersion.apiLevel = 23
           versionCode = 1
           versionName = "1.0"
       }
       buildTypes {
           release {
               minifyEnabled false
               proguardFiles.add(file('proguard-android.txt'))
           }
       }
   }
}
// others below this line: no change

NOTE: the version numbers may be different on your system, and you do not need to change the version number -- just use them as is. Only changing the highlighted part would be fine!

  1. Sync , Build and Run . You should still see the same "Hello World" on your target device.

4. Add JNI Code Into Project

  1. Check the NDK Path.
    Select the menu "File" > "Project Structure" > "SDK Location", "Android NDK Location" if it is not set yet, then click "...", and browse to your NDK location and click "OK" (you may also choose "download").
  2. Configure the module build.gradle to create "hello-android-jni" shared lib.
    Select Android Studio "Project" pane > "Gradle Scripts" > "build.gradle (Module:app)", add the following inside the "model" block, after "buildTypes" block.
buildTypes {
...
}
// New code
ndk {
    moduleName "hello-android-jni"
}
// New code finished
  1. Add JNI function and load jni shared lib into project.
    Select Android Studio "Project" pane > "app" > "java" > "com.google.sample.helloandroidjni" > "MainActivity", and add JNI function getMsgFromJni() and System.loadLibrary() to the end of class MainActivity.
...
   // new code
   static {
       System.loadLibrary("hello-android-jni");
   }
   public native String getMsgFromJni();
   // new code done
} // class MainActivity
  1. Sync , Build , there should be no errors from Android Studio.

Note:

  • make sure library name is the same as moduleName inside build.gradle
  • The "Build" step
  1. Generate the C/C++ prototype function for jni function getMsgFromJni().
    In MainActivity.java file, "getMsgFromJni()" is highlighed with red because Android Studio could not find its implementation; let's get it implemented:
  • Select function "getMsgFromJni()".
  • Wait for context aware menu prompt to appear.
  • Click on to bring up the popup menu.
  • Select "Create Function Java_com_google_example_helloandroidjni_MainActivity_getMsgFromJni".
  • Android Studio creates a prototype function for getMsgFromJNI() in hello-android-jni.c file under the "jni" folder. Both got created at once!
#include <jni.h>

JNIEXPORT jstring JNICALL
Java_com_google_sample_helloandroidjni_MainActivity_getMsgFromJni(JNIEnv *env, jobject instance) {

   // TODO
  
   return (*env)->NewStringUTF(env, returnValue);
}
  • Replace "returnValue" in the above code with our own message:
// TODO
return (*env)->NewStringUTF(env, "Hello From Jni");
  1. Display our JNI message in the application.
  • Add an ID to the existing TextView.
    Open "Android Studio" pane, "res" > "layout" > "content_main.xml"[if you have chosen template "Empty Activity" in step "Create Java Sample App", you file might be "activity_main.xml" instead], select "design" view, and click or "Hello World", inside "Properties" pane, put "@+id/jni_msgView" into "ID" field:

    [The other way is to directly add into "text" view, and put id in with android:id="@+id/jni_msgView".]
  • Display our jni message in the TextView.
    In MainActivity::onCreate() function, append following code to the end of the function:
((TextView) findViewById(R.id.jni_msgView)).setText(getMsgFromJni());
  1. Click the Run button, you should see "Hello From Jni" in your target device.
  2. Browse the Native Code
  • Select "NewStringUTF" inside hello-android-jni.c, "right click" to bring up the pop-up menu.
  • Select "Go To", and "Implementation(s)".
  • You will see the function implementation of "NewStringUTF".
  • Select other code to explore the native code browsing feature.

5. Debugging JNI Code

  1. Click the Run/Debug Configuration
    [For Android Studio version earlier than 2.2, select . Android Studio auto-generates this native debug configuration when it detects JNI code. In this config, debug configurations are enabled by default. If is not visible, close this project and reopen it with Android Studio, it will be there; Android Studio version 2.2 integrated the debug functionality into app configure].
  2. Open hello-android-jni.c inside Android Studio.
  3. Click the left edge of the native code to set a breakpoint: 
  4. Click the Debug button, your android device should prompt "Waiting For Debugger" message:
  5. Wait until Android Studio connects to the debugger on your device ( it might take 1 - 2 minutes, depending on the device and OS version ), and stops at the breakpoint. 
  6. Click "env" inside the "Variables" window at the bottom pane of Android Studio to observe contents of envpointer.
  7. Click "+" at the bottom of the "Watches" window (next to "Variables") and add "env", Android Studio will bring the content of env into watch window. The values should be the same as the values in "Variables" window.
  8. Click the "F8" key to step over, and menu "Run" > "Resume Program" to continue the execution.

[Note: if you are using Android Studio RC 1.5 or better, you can set a breakpoint on getMsgFromJni() in Java code and "trace into" JNI code]

6. Congratulations!

Your app is now ready to use Android Studio for your Native project development!

What we've covered with Android Studio

  • Create a JNI project
  • Debug native code in JNI project

Next Steps

Learn More

本文转载自:https://codelabs.developers.google.com/codelabs/android-studio-jni/index.html?index=..%2F..%2Find...

共有 人打赏支持
nextowang
粉丝 0
博文 7
码字总数 12120
作品 0
西安
程序员
Android: NDK编程入门笔记

为何要用到NDK? 概括来说主要分为以下几种情况: 1. 代码的保护,由于apk的java层代码很容易被反编译,而C/C++库反汇难度较大。 2. 在NDK中调用第三方C/C++库,因为大部分的开源库都是用C/C...

gongweixin
2013/04/23
0
3
Android: NDK编程入门笔记

为何要用到NDK? 概括来说主要分为以下几种情况: 1. 代码的保护,由于apk的java层代码很容易被反编译,而C/C++库反汇难度较大。 2. 在NDK中调用第三方C/C++库,因为大部分的开源库都是用C/C...

xubohui
2012/08/20
0
0
Android: NDK编程入门笔记

为何要用到NDK? 概括来说主要分为以下几种情况: 1. 代码的保护,由于apk的java层代码很容易被反编译,而C/C++库反汇难度较大。 2. 在NDK中调用第三方C/C++库,因为大部分的开源库都是用C/C...

JORDANSG
2012/08/14
0
0
linux 命令行下 使用android sdk 以及ndk

环境 首先保证已经安装了java,sdk,ndk 相关的一些包,并有类似如下的配置: export NDK_ROOT=/home/develop/android-ndk-r9cexport SDKROOT=/home/develop/adt-bundle-linux-x8664-20131030/s......

不写可以么
2014/01/25
0
0
如何为Android,Mac和Windows平台创建Java JNI动态链接库

Java Native Interface (JNI) 是Java和C/C++之间的桥梁。在一些情况下,为了提高Java程序的性能,扩展Java程序的功能,我们需要使用JNI。比如数据库的调用,当我们下载一个JDBC的jar包之后,...

yushulx
2014/09/17
0
0
android 最新 NDK r8 在window下开发环境搭建

android 最新 NDK r8 在window下开发环境搭建 安装配置与使用 详细图文讲解,完整实际配置过程记录(原创) 一直想搞NDK开发却一直给其他事情耽搁了,参考了些网上的资料今天终于把环境搭建起来...

lxp198837
2014/04/23
0
0
Cygwin+Eclipse+Android NDK ---Windows

近几天看JNI的问题,都说要怎么编译,要输入很多命令行的东西。我觉得既然有IDE应用开发环境,就会有相应的JNI开发,很方便的不必输入什么命令行的。 SDK应用常用的编译环境是Eclipse,然后就...

刘遇安
2013/03/30
0
0
Android Studio 使用NDK开发

Android Studio 使用NDK编程 使用Android Studio有半年多了,感觉很好用,不就感觉费劲的就是NDK的支持一直不是很好,再Bate版的时候好像0.4.x之前可以使用NDK,当然本身Android Studio本身是...

HaidyCao
2014/12/21
0
17
HelloWorld App of ffmpeg JNI

HelloWorld App of ffmpeg JNI (1)、用eclipse导入NDK 示例Samples中的helloJNI工程 (2)、将编译的ffmpeg源代码复制到工程目录中的jni目录中 (3)、修改HelloJni.java代码为: /* Copyr...

huntking
2012/09/25
0
0
Android JNI学习(二)——实战JNI之“hello world”

本系列文章如下: Android JNI(一)——NDK与JNI基础 Android JNI学习(二)——实战JNI之“hello world” Android JNI学习(三)——Java与Native相互调用 Android JNI学习(四)——JNI的常用方法...

隔壁老李头
05/09
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

Confluence 6 安装补丁类文件

Atlassian 支持或者 Atlassian 缺陷修复小组可能针对有一些关键问题会提供补丁来解决这些问题,但是这些问题还没有放到下一个更新版本中。这些问题将会使用 Class 类文件同时在官方 Jira bug...

honeymose
10分钟前
0
0
设计模式:代理模式

代理模式可以分为三种:静态代理,动态代理,cglib代理 1.静态代理:被代理的类需要实现一接口或是继承一父类 委托类(被代理的类): package com.java.pattern.proxy.staticdemo;publ...

人觉非常君
13分钟前
0
0
非常实用的IDEA插件之总结

1、Alibaba Java Coding Guidelines 经过247天的持续研发,阿里巴巴于10月14日在杭州云栖大会上,正式发布众所期待的《阿里巴巴Java开发规约》扫描插件!该插件由阿里巴巴P3C项目组研发。P3C...

Gibbons
19分钟前
0
0
Tomcat介绍,安装jdk,安装tomcat,配置Tomcat监听80端口

Tomcat介绍 Tomcat是Apache软件基金会(Apache Software Foundation)的Jakarta项目中的一个核心项目,由Apache、Sun和其他一些公司及个人共同开发而成。 java程序写的网站用tomcat+jdk来运行...

TaoXu
19分钟前
0
0
TensorFlow,从一个 Android Demo 开始

TensorFlow Android Demo 项目地址 Machine Learning 既然提到了 TensorFlow,那是不是得神经网络、机器学习了解下? 如果你能坚持把 机器学习速成课程 给啃完了,觉得还挺有兴趣的,那可以考...

孟飞阳
21分钟前
0
0
JVM学习笔记二:内存结构规范

1、JVM基本结构图 2、java堆(Heap) 3、方法区(Method Area) 4、程序计数器 5、JAVA栈图解 局部变量表:八大基本类型,还可以存储引用类型 上一篇:JVM学习笔记一:类加载机制介绍...

刘祖鹏
26分钟前
0
0
mui集成微信H5支付(返回白屏问题已经解决)

一.项目需求 因为公司人员缺少,没有专门开发安卓和ios的人员,为了项目尽早上线采用了混合APP开发的方式,我选择了MUI混合开发框架,项目中需要在用户购买VIP会员的时候进行支付,所以需要在项目...

银装素裹
30分钟前
0
0
TensorFlow gpu 版 安装

win10 + Python3.6 下载cuda https://developer.nvidia.com/cuda-downloads?target_os=Windows&target_arch=x86_64&target_version=81&target_type=exelocal 下载cudnn,复制链接地址,使用迅......

阿豪boy
49分钟前
0
0
SpringBoot集成Redis--配置自定义的RedisCacheManager

配置自定义的RedisCacheManager--1自定义键生成规则 默认的键生成器 当不指定缓存的key时,SpringBoot会使用SimpleKeyGenerator生成key。 SimpleKeyGenerator SimpleKey 查看源码可以发现,它...

karma123
49分钟前
0
0
防火墙未来的发展趋势在哪里?

导读 防火墙(Firewall),也称防护墙,是由Check Point创立者Gil Shwed于1993年发明并引入国际互联网。当下互联网时代,无论是大小企业,大部分都会部署有防火墙的设备,但这些防火墙往往并不...

问题终结者
52分钟前
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部