У меня есть проект на C ++, и я хочу использовать его в своем приложении для Android.
Создано новое приложение в соответствии с инструкциями Google :
- В разделе мастера «Выберите проект» выберите тип проекта Native C ++.
- Нажмите кнопку Далее.
- Заполните все остальные поля в следующем разделе мастера.
- Нажмите кнопку Далее.
- В разделе Настройка поддержки C ++ мастераВы можете настроить свой проект с помощью поля C ++ Standard.Используйте раскрывающийся список, чтобы выбрать, какую стандартизацию C ++ вы хотите использовать.При выборе Toolchain Default используется настройка CMake по умолчанию.
- Нажмите Finish.
Вот проект, с которым я закончил: (Я ничего не изменил, так что должно бытьgeneric)
native-lib.cpp:
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring JNICALL
Java_e_viktor_testinggitapplication_MainActivity_stringFromJNI(JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
MainActivity.java:
package e.viktor.testinggitapplication;
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 = 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();
}
Здесь я только добавил версию cmake
Gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "e.viktor.testinggitapplication"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
version "3.10.2"
cppFlags ""
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
CMakeLists.txt:
cmake_minimum_required(VERSION 3.4.1)
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)
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)
target_link_libraries( # Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib})
В результате - «Не удается разрешить соответствующую функцию JNI» в MainActivity.java
и
«Не удается найти поле» для всех #include и «Не удается определить тип» для всех типов в файле cpp.
Интересно то, что gradle успешно строится.
Редактировать:
Добавлен CMakeLists.txt