在android studio中创建Hello-JNI工程
2016-07-23 00:00
489 查看
摘要: 本文为Google codelabs中,引用C++文件在android studio 2.2 preview4中创建Jni的android工程的翻译文档,为了方便后续关于android studio2.2中添加OpenCV模块提供引用支持。
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+.
a) Linux: Run
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.
Select "Start a new Android Studio project".
On "New Project" page, change "Application Name" to HelloAndroidJni, and leave the default values for other fields.
Click "Next", select "Basic Activity" as our template in "Add an Activity to Mobile" page
Click "Next" all the way to "Finish" to complete application creation.
This creates an Android "Hello World" Java app; your Android Studio looks like:
(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.
Sync
, Build
and Run
, you will see the following on your target device or Emulator:
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".
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
Sync
, Build
and Run
, you should see the same as in step 6.
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.
Replace gradle plugin
with your latest version[it does not have to be 0.7.2]:
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:
to:
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:
with:
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!
Sync
, Build
and Run
. You should still see the same "Hello World" on your target device.
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").
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 "
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.
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
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!
Replace "returnValue" in the above code with our own message:
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:
Click the
Run button, you should see "Hello From Jni" in your target device.
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.
[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].
Open hello-android-jni.c inside Android Studio.
Click the left edge of the native code to set a breakpoint:
Click the Debug button
, your android device should prompt "Waiting For Debugger" message:
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.
Click "env" inside the "Variables" window at the bottom pane of Android Studio to observe contents of
Click "+" at the bottom of the "Watches" window (next to "Variables") and add "
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]
Debug native code in JNI project
Reference to detailed online document for gradle-experimental SDL syntax
Explore Android Studio samples, google play game samples, and vulkan samples
Learn Android NDK and SDK.
Explore more NDK, Vulkan tutorials, Vulkan API, and Play games samples on github.
Google IO 2015 Presentation for Android Studio.
Post questions to Android Tools Team
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
Find and start Android Studio on your development system:a) Linux: Run
studio.shfrom 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.
Select "Start a new Android Studio project".
On "New Project" page, change "Application Name" to HelloAndroidJni, and leave the default values for other fields.
Click "Next", select "Basic Activity" as our template in "Add an Activity to Mobile" page
Click "Next" all the way to "Finish" to complete application creation.
This creates an Android "Hello World" Java app; your Android Studio looks like:
(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.
Sync
, Build
and Run
, you will see the following on your target device or Emulator:
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".
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
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.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.
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'
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
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!
Sync
, Build
and Run
. You should still see the same "Hello World" on your target device.
4. Add JNI Code Into Project
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").
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
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
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
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");
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());
Click the
Run button, you should see "Hello From Jni" in your target device.
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
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].
Open hello-android-jni.c inside Android Studio.
Click the left edge of the native code to set a breakpoint:
Click the Debug button
, your android device should prompt "Waiting For Debugger" message:
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.
Click "env" inside the "Variables" window at the bottom pane of Android Studio to observe contents of
envpointer.
Click "+" at the bottom of the "Watches" window (next to "Variables") and add "
env", Android Studio will bring the content of
envinto watch window. The values should be the same as the values in "Variables" window.
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 projectDebug native code in JNI project
Next Steps
Adopt Android Studio to your Android Native project environmentReference to detailed online document for gradle-experimental SDL syntax
Explore Android Studio samples, google play game samples, and vulkan samples
Learn More
Learn how to use Android Studio.Learn Android NDK and SDK.
Explore more NDK, Vulkan tutorials, Vulkan API, and Play games samples on github.
Google IO 2015 Presentation for Android Studio.
Post questions to Android Tools Team
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Native 绘图方法
- SourceProvider.getJniDirectories
- 执行失败的任务 ': processDebugManifest'
- Android Studio使用教程(六):Gradle多渠道打包
- Android NDK开发之:配置环境的详解
- Android客户端程序Gradle如何打包
- Android开发的IDE、ADT、SDK、JDK、NDK等名词解释
- Android提高之使用NDK把彩图转换灰度图的方法
- Android使用Jni实现压力锅数据检测效果示例
- Android中使用Gradle来构建App项目的入门指南
- Android NDK 生成以及调用so 文件
- Android App开发中Gradle构建过程的配置方法
- Android Studio使用教程(四):Gradle基础
- Android Studio使用教程(五):Gradle命令详解和导入第三方包
- JAVA中JNI的简单使用分享
- c++ mk文件出错Jni调用产生java.lang.UnsatisfiedLinkError错误解决方法
- 解析Java的JNI编程中的对象引用与内存泄漏问题
- 探讨:如何在NDK中呼叫Java的class