Android调用C代码by Netfairy - 2016-11-02
MainActivity.java:
package com.example.netfairy.test;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.AlertDialog;
public class MainActivity extends AppCompatActivity {
private static final String libSoName = "NDK_03";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CallNativeMethon();
}
private void CallNativeMethon() {
new AlertDialog.Builder(MainActivity.this)
.setTitle("计算结果")
.setMessage("1+2="+Integer.toString(add(1,2))) //调用
.setPositiveButton("确定", null)
.show();
}
//声明native函数
public native int add(int x, int y);
static
{
System.loadLibrary(libSoName);
}
}
build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.0"
defaultConfig {
applicationId "com.nowsecure.android.vts"
minSdkVersion 15
targetSdkVersion 23
versionCode 13
versionName "v.13"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets.main {
jni.srcDirs = [] // This prevents the auto generation of Android.mk
// This tells gradle to include the objects in libs/ which were generated by running our
// Android.mk basically by shelling out
jniLibs.srcDir 'src/main/libs'
}
}
android {
packagingOptions {
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
}
repositories {
maven { url "https://jitpack.io" }
flatDir{
dirs 'libs'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:cardview-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.github.paolorotolo:appintro:3.3.0'
}
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
def ndkDir = properties.getProperty('ndk.dir')
task buildNative(type: Exec, description: 'Compile JNI source via NDK') {
commandLine "C:\\Android\\ndk\\ndk-build.cmd",
'-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
'-j', Runtime.runtime.availableProcessors()
}
task cleanNative(type: Exec, description: 'Clean JNI object files') {
commandLine "C:\\Android\\ndk\\ndk-build.cmd",
'-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
'clean'
}
clean.dependsOn 'cleanNative'
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn buildNative
}
main/jni/Operate.c
#include
int add(int x, int y) {
return x+y;
}
jint Java_com_example_netfairy_test_MainActivity_add(JNIEnv* env, jobject thiz,jint x,jint y)
{
return add(x,y);
}
main/jni/Android.mk:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_LDLIBS += -L$(SYSROOT)/usr/lib -llog
LOCAL_MODULE := NDK_03
LOCAL_SRC_FILES := \
Operate.c
include $(BUILD_SHARED_LIBRARY)