【转】Create Hello-JNI with Android Studio

From:https://codelabs.developers.google.com/codelabs/android-studio-jni/index.html?index=..%2F..%2Findex#4

访问需要FQ。

没有翻译成中文是因为图片很详细,看不懂英文,根据图片一步一步也能完成。另外开发人员应该具备阅读英文技术博客的能力。

1. Overview

In this codelab, you'll learn how to use Android Studio to start Android NDK project development.

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 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 codestatic {System.loadLibrary("hello-android-jni");}publicnativeString 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 is just to build, do not load the built apk yet; if you load it, it will crash since there is no native implementation for getMsgFromJni() yet
  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

  • 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 env pointer.
  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]

项目源码 https://github.com/leon-HM/HelloAndroidJni

转载于:https://www.cnblogs.com/leon-hm/p/6472537.html

【转】Create Hello-JNI with Android Studio相关推荐

  1. android ndk jni so,Android Studio Ndk So 文件

    一 下载NKD,并解压 官网:https://developer.android.com/index.html 二 新建项目 1 新建Android Studio项目 2 项目配置NDK路径 imag ...

  2. 安卓 jni 开发 —— Android Studio 打包 so 的坑

    博客: 安卓之家 微博: 追风917 CSDN: 蒋朋的家 简书: 追风917 安卓开发坑无限 我心依旧,不变 向前 jni 开发的坑 这两天要搞安卓下的串口读写,这块涉及到了 jni 开发,我找了两 ...

  3. Android JNI for Android Studio 2.2 or higher

    点击浏览 官网说明 (要翻墙) 安装插件 需要打开SDK Manager 菜单栏 Tools>Android>SDK Manager 点击切换到 SDK Tools 选项卡 勾选 LLDB ...

  4. androidstudio调试android 源码 jni,在android studio下配置gradle用ndk-build和ndk-gbd编译调试JNI...

    因为要在旧版android在做一些工作.所以做用到了它.目标平台是:android api 10和armv6. 开发环境是:AS 版本2.3.2; SDK版配android 2.3.3(api10); ...

  5. android studio jni so,Android studio JNI 制做SO文件,在其余项目中调用

    这些目录下,每一个下面都会有so文件.区别在于不一样设备,会调用不一样包下面的文件.(这点我也不清楚,不浅学误人) 2.新建项目,将armeabi连同下面的so文件,放入项目的libs下. java代 ...

  6. 在android studio中创建Hello-JNI工程

    2019独角兽企业重金招聘Python工程师标准>>> 1. Overview What you'll need : Android Studio 2.2 or higher fro ...

  7. Android Studio 3.6 发布啦,快来围观

    Android Studio 3.6 稳定版终于来了,此版本的 Android Studio 包括对一些设计工具的更新,包括布局编辑器和资源管理器. 该版本的更新需要 Plugin 对应更新支持,比如 ...

  8. eclipse项目迁移到Android Studio

    由于公司项目需要多包名APK的支持,所以把公司的项目从eclipse迁移到了Android Studio. 以下是一些迁移经验: 迁移准备 Android Studio对代码检查比较严格,代码中如果存 ...

  9. Android Studio制作.9图片,看这一篇就够了

    一..9.png图片概念 这是安卓开发里面的一种特殊的图片 这种格式的图片在android 环境下具有自适应调节大小的能力,不会失真 (1)允许开发人员定义可扩展区域,当需要延伸图片以填充比图片本身更 ...

最新文章

  1. [洛谷P2742]【模板】二维凸包([USACO5.1]圈奶牛Fencing the Cows)
  2. Java基础/利用fastjson序列化对象为JSON
  3. 批量修改MSSQL架构名称
  4. 释疑の字段符号 FIELD-SYMBOLS
  5. Google Apps – Framework, Phonesky, GmsCore w/ AOSP Build.
  6. axure类型app项目rp文件_Python编程快速上手实践项目--选择性拷贝指定类型文件到目的目录...
  7. c#设计模式-建造者模式
  8. IIS 7.5出现500.19错误解决方法
  9. linux weblogic java_options_使用Linux脚本更新Weblogic部署的应用程序
  10. ES11新特性_String.prototype.matchAll方法---JavaScript_ECMAScript_ES6-ES11新特性工作笔记063
  11. JUnit 5 Alpha版本简化了单元测试
  12. NI Teststand 2014 64bit 调用python脚本指南
  13. golang 修改全局默认时区的方法
  14. C++中 =defaule 和 =delete 使用
  15. 如何建立起一套有效的APP监控体系
  16. 【C语言】三子棋(智能下棋 + 阻拦玩家)
  17. 类之间的继承java,Java类与类之间的继承关系
  18. 2022大学生就业指导答案——雷五明、雷辉等
  19. 《李焕英》爆火背后,世界正在奖励那些诚实的人
  20. 反脆弱 : 如何在复杂世界越变越强

热门文章

  1. Linux (七) 网络
  2. 【Python1】双系统安装,深度学习环境搭建,目标检测(Tensorflow_API_SSD)
  3. 基于jsp+javabean+servlet的二手物品交易系统_基于Jsp+Servlet的商城系统
  4. python 写入第二列_python读写Excel表格的实例代码(简单实用)
  5. 电脑下面的任务栏怎么取消隐藏_电脑桌面右下方任务栏的小图标如何隐藏
  6. 【读书笔记】阅读的危险
  7. 三角形最小路径和—leetcode120
  8. mysql 1280_技术分享 | MySQL 一次奇怪的故障分析
  9. Codeforces Round #528 (Div. 2) - D. Minimum Diameter Tree
  10. 快速排序(C++版)