In today's video, we'll walk through integrating a C++ file into an existing Android project and displaying its content in the activity.
Watch the Video Tutorial
If you prefer a step-by-step walkthrough, watch the video tutorial below:
Step-by-Step Integration
1. Set Up Your Project
Start by opening your project hierarchy. Click on Android, then Project. Right-click on app and create a new directory named CPP. Inside this directory, create a new file named CMakeLists.txt. Make sure the name is exact to avoid errors later.
2. Configure CMakeLists.txt
Add the following CMake version and configuration to the CMakeLists.txt file:
cmake_minimum_required(VERSION 3.10.2)
project(ChannelDetails)
add_library(channel_details SHARED channel_details.cpp)
find_library(log-lib log)
target_link_libraries(channel_details ${log-lib})
3. Update build.gradle
In your build.gradle file, add a new block for externalNativeBuild:
android {
...
externalNativeBuild {
cmake {
path "src/main/cpp/CMakeLists.txt"
}
}
}
Sync your project after making these changes.
4. Move and Update the C++ File
Move the channel_details.cpp file into the cpp directory. Update this file to be compatible with JNI. Replace iostream
with jni.h
, and modify the method to use JNI conventions:
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_myapp_MainActivity_getChannelDetails(JNIEnv *env, jobject obj) {
std::string channelName = "Example Channel";
return env->NewStringUTF(channelName.c_str());
}
5. Update MainActivity
In your MainActivity class, load the native library and declare the native method:
static {
System.loadLibrary("channel_details");
}
public native String getChannelDetails();
Call this method to retrieve and display the channel name:
TextView channelNameTextView = findViewById(R.id.channel_name);
channelNameTextView.setText(getChannelDetails());
6. Run Your Application
Run your application to see the returned string from the C++ code displayed in your activity.
No comments:
Post a Comment
Share your thoughts ...