文档章节

在android studio中创建Hello-JNI工程

nextowang
 nextowang
发布于 2016/07/23 16:33
字数 1352
阅读 166
收藏 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
粉丝 1
博文 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 NDK Hello

Android应用程序访问android的根文件系统中的文件时,由于应用程序的权限限制,无法访问这些文件,怎么办? 这时就要用到NDK编程了,既用C/C++代码实现访问系统文件,并将其生成本地库,供a...

长平狐
2013/01/06
130
0

没有更多内容

加载失败,请刷新页面

加载更多

《阿里铁军》的读书笔记和读后感范文2600字

《阿里铁军》的读书笔记和读后感范文2600字: 在中国互联网,有一个流传很广的说法是,百度强在技术,腾讯强在产品,阿里强在运营。虽然发展到今天,已经不能再用这样简单的视角来看待这三个...

原创小博客
28分钟前
2
0
怎样实际项目中运用责任链模式

1 模式概要 1.1 简介 责任链模式为请求创建一个接收者对象链,每个接收者都包含对另一个接收者的引用,如果一个对象不能处理该请求,那么它会把请求传给下一个接收者,依此类推 责任链模式避...

小刀爱编程
43分钟前
2
0
【宇润日常疯测-004】JS 遍历数组如何快!快!快!

首先,我就是一后端全栈,对前端也只是会用罢了。闲的无聊来测测,不深究,只看表面,不喜勿喷! 遍历数组在写 JS 代码时候一定是经常用的,那么怎么遍历能达到最高效率呢,很多人一定没有测...

宇润
47分钟前
11
2
Linux系统如何定制History输出格式

Linux系统使用History命令来查看系统的运行记录,从而找出一些问题。但是History输出的数据中常常没有时间等信息。本文就来教大家Linux系统如何定制History输出格式。   具体方法如下 以r...

linuxprobe16
49分钟前
2
0
(一) pyhon 基础语法(数值 字符串 元组 列表 字典)

1、python的数据类型: 数值 字符串 列表 元组 字典; 数值类型包括; 整型(int) 长整型(long) 浮点型(float) 复数型 字符串; 可以通过type() 来查看是什么类型的; 注释:len()只支持 字符...

芬野de博客
49分钟前
2
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部