2019独角兽企业重金招聘Python工程师标准>>>

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 23buildToolsVersion "23.0.1"defaultConfig {applicationId "com.google.sample.helloandroidjni"minSdkVersion 22targetSdkVersion 23versionCode 1versionName "1.0"}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'}}
}
// others below this line: no change

with:

apply plugin: 'com.android.model.application'model {android {compileSdkVersion = 23buildToolsVersion = "23.0.3"defaultConfig {applicationId = "com.google.sample.helloandroidjni"minSdkVersion.apiLevel = 22targetSdkVersion.apiLevel = 23versionCode = 1versionName = "1.0"}buildTypes {release {minifyEnabled falseproguardFiles.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 codestatic {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) {// TODOreturn (*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

  • Adopt Android Studio to your Android Native project environment
  • Reference 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

转载于:https://my.oschina.net/nextowang/blog/716687

在android studio中创建Hello-JNI工程相关推荐

  1. android studio建数据库表,在android studio中创建表

    错误:android.database.sqlite.SQLiteException:表用户没有列名(代码1):编译时:INSERT INTO用户名(名称,余额,密码,年龄)VALUES(? ?,?, ...

  2. 使用Kotlin在Android Studio中创建井字游戏

    井字游戏也被称为"Noughts和crosses".它是两个玩家最普遍的纸笔游戏之一. 它主要由年幼的孩子放置,但很多时候,你也可以看到成年人玩这个来切断无聊.这个游戏非常方便,可 ...

  3. 在 Android Studio 中创建一个简单的 QQ 登录界面

    一,创建一个新的 Android Studio 项目 打开 Android Studio,选择 "Start a new Android Studio project",然后填写应 ...

  4. android studio中创建、切换svn分支

    偶尔翻到一篇之前的笔记,虽然早已经从svn专用git了,但还是分享出来给那些还坚守svn的小伙伴吧. 相对于git,svn的分支管理就没那么简单方便,所以总结一些在Android Studio上使用s ...

  5. android studio创建文件,如何在Android Studio中创建File Templates

    标签: File Template Android Studio 我发现一个可以让写程序变得简单的方法,那就是自定义文件模板(Custom File Templates).那么什么是File Temp ...

  6. android flutter 环境,Android Studio 中创建Flutter环境配置(Mac环境)

    1.先下载Flutter 的SDK ,网页中有打包好的SDK(https://flutter.io/setup-macos/) 2.设置PATH 代码下载之后在终端中打开bash_profile文件 ...

  7. Android源码编译Android Studio(带jar和jni)工程

    1.把android studio工程删除到如下目录, 注意:如果在此目录下,有libs和jni目录 # cp -rf jni app/src/main # cp -rf libs app/src/m ...

  8. 在android studio中如何创建一个类来继承另外一个类_在Android使用Transition API检测用户活动...

    在当今世界,移动设备是我们日常生活中必不可少的一部分,我们在走路.跑步.开车以及其他许多活动时都会使用移动设备. 了解用户拿着手机的时候在做什么,可以让你的应用程序根据用户的动作进行直观的调整.对于某 ...

  9. android studio中把c/c++文件编译成.so库(一)

    2019独角兽企业重金招聘Python工程师标准>>> 最近的项目涉及到JNI编程,经过一段时间的JNI编程之后,终于完美弄完了.所以,把在android studio中编译c/c+ ...

最新文章

  1. faiss(1):简介 安装 与 原理
  2. CascadingStyleSheets
  3. python 数据挖掘 简书_[Python数据挖掘入门与实践]-第一章开启数据挖掘之旅
  4. java 多线程下载文件并实时计算下载百分比(断点续传)
  5. 导入Oracle 数据库镜像,创建Oracle虚拟机_01
  6. 求出m~n的整数中1出现的次数
  7. EasyUI-基本框架
  8. WebStorm中文HTML编辑开发工具
  9. c语言中为什么无法打开原文件格式,为什么vs2012无法打开源文件graphics.h和bio
  10. html预览pdf上的电子印章,移动端pdf预览-水印电子签章问题
  11. iphone5s显示被停用了解决办法
  12. uniapp苹果无法上架_uniapp无法上架IOS包怎么办
  13. 《嵌入式 – GD32开发实战指南》第9章 呼吸灯
  14. c语言编写时钟图案,用C语言绘制电子时钟图案
  15. 你的计算机无法启动怎么回事,电脑无法正常启动如何做系统-“你的电脑未能正确启动”的解决方法...
  16. Java面试之JVM
  17. 从零开始用C语言实现图片解码播放器(有源码)
  18. Semantic Parsing via Staged Query Graph Generation: Question Answering with Knowledge Base(笔记)
  19. 基于Visual C++2010 与office2010开发办公自动化(14)-自定义excel2010工具栏
  20. 干物妹小埋-树状数组-吉首大学2019年程序设计竞赛

热门文章

  1. sniffer 工具
  2. Linux终端操作MySQL常用命令
  3. python06: 运算符. if
  4. Weex Ui - Weex Conf 2018 干货分享
  5. python3----列表
  6. Google Chrome Native Messaging开发实录(一)背景介绍
  7. Swift - 获取、改变按钮的标题文本(UIButton点击切换title)
  8. matlab 中max函数用法
  9. 算法训练 Torry的困惑
  10. 正则在php中的使用