Android NDK开发入门

原创
2019/09/30 07:51
阅读数 394

环境:Android Studio 2.3。

创建项目

别忘了选择“Include C++ Support”。

输入图片说明

创建好项目后,项目结构如下:

输入图片说明

(忽略CalculateService,这是后面添加的)

MainActivity内容如下:

package com.example.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv = (TextView) findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
}

stringFromJNI函数需要在C/C++进行实现。在native-lib.cpp中已经实现好了。

#include <jni.h>
#include <string>

extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_myapplication_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

项目的buid.gradle内容如下:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.example.myapplication"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt" // 注意这里
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

CMakeLists.txt内容如下:

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
             native-lib

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             src/main/cpp/native-lib.cpp )

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
              log-lib

              # Specifies the name of the NDK library that
              # you want CMake to locate.
              log )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
                       native-lib

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )

运行项目,效果如下:

输入图片说明

添加按钮,计算数据

创建 CalculateService.java ,添加native add方法,文件内容如下:

package com.example.myapplication;

public class CalculateService {

    public native int add(int first, int second);

}

鼠标点击add,使用快捷键Alt+Enter,弹出菜单中点击第一个。

输入图片说明

native-lib.cpp中会添加如下内容:

JNIEXPORT jint JNICALL
Java_com_example_myapplication_CalculateService_add(JNIEnv *env, jobject instance, jint first,  jint second) {

    // TODO

}

略作修改后文件内容如下:

#include <jni.h>
#include <string>

extern "C" {

JNIEXPORT jstring JNICALL
Java_com_example_myapplication_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

JNIEXPORT jint JNICALL
Java_com_example_myapplication_CalculateService_add(JNIEnv *env, jobject instance, jint first, jint second) {
    return first+second;
}

} // end extern

运行效果:

输入图片说明

C++调用Toast展示计算结果

重写按钮的点击事件:

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CalculateService calculateService = new CalculateService();
                int result = calculateService.add(1, 2);
                Log.v("MainActivity", "result: "+result);
            }
        });

定义Toast工具类ToastUtil.java:

package com.example.myapplication;

import android.content.Context;
import android.widget.Toast;

public class ToastUtil {

    public ToastUtil() {

    }

    public void shortShow(String msg) {
        Context context = MyApplication.getAppContext();
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

}

MyApplication.getAppContext()得到一个全局的Context,具体实现见代码。

这里遇到一个坑。自定义Application后需要在AndroidManifest.xml 中设置新的Application。但是设置后编译运行一直没有生效。解决方法很简单实用:clean project。这个可以解决很多疑难杂症。

修改native-lib.cpp:

#include <jni.h>
#include <string>
#include <iostream>
#include <sstream>

using namespace std;

namespace patch
{
    template < typename T > string to_string( const T& n )
    {
        std::ostringstream stm ;
        stm << n ;
        return stm.str() ;
    }
}


class ToastUtil {
public:
    ToastUtil(JNIEnv *env) {
        this->env = env;
    };
    void shortShow(string msg) {
        jclass cls = env->FindClass("com/example/myapplication/ToastUtil");
        jmethodID ctor = env->GetMethodID(cls, "<init>", "()V");  // 构造函数,用<init>表示
        jobject obj_toastUtil = env->NewObject(cls, ctor);  // 创建 ToastUtil 实例
        jmethodID func_shortShow = env->GetMethodID(cls, "shortShow", "(Ljava/lang/String;)V");
        env->CallVoidMethod(obj_toastUtil, func_shortShow, env->NewStringUTF(msg.c_str()));
    };
private:
    JNIEnv *env;
};

extern "C" {

JNIEXPORT jstring JNICALL
Java_com_example_myapplication_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

JNIEXPORT jint JNICALL
Java_com_example_myapplication_CalculateService_add(JNIEnv *env, jobject instance, jint first, jint second) {
    jint result = first + second;
    ToastUtil toastUtil(env);
    toastUtil.shortShow(string("计算结果:" + patch::to_string((int)result)));
    return result;
}

} // end extern

运行效果:

输入图片说明

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部