一個沒用過java和安卓的人使用android studio開發帶c++ so庫的安卓程序用例(以ndk的hello-jni為例),對於不熟悉java和安卓的人來說這個很花時間,希望通過這篇文章幫助跟我一樣的人,歡迎隨便轉載:
1.下載安裝android sdk和ndk,ndk r10(目前最新)是單獨可以編譯c++的,無需cygwin。
2.安裝android studio。
3.通過ndk-build命令編譯sample中的hello-jni,生成so庫。
4.在android studio新建項目,把生成的全部so文件連同處理器文件夾一同拷貝到項目的libs文件中。修改build.gradle文件,添加sourceSets,內容如下:
apply plugin: 'com.android.application' android { compileSdkVersion 21 buildToolsVersion "21.1.2" defaultConfig { applicationId "com.sample.hello" minSdkVersion 15 targetSdkVersion 21 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } sourceSets { main { jniLibs.srcDirs = ['libs'] } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:21.0.3' }
5.添加java文件hellojni文件(注意package):

基本拷貝的sample中的hellojni文件,代碼如下(
該代碼略有不同,我給stringFromJNI傳string參數,可自行參考ndk中sample/src中的hellojni文件):
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.hellojni; public class HelloJni { /* A native method that is implemented by the * 'hello-jni' native library, which is packaged * with this application. */ public native String stringFromJNI(String msg); /* This is another native method declaration that is *not* * implemented by 'hello-jni'. This is simply to show that * you can declare as many native methods in your Java code * as you want, their implementation is searched in the * currently loaded native libraries only the first time * you call them. * * Trying to call this function will result in a * java.lang.UnsatisfiedLinkError exception ! */ public native String unimplementedStringFromJNI(); /* this is used to load the 'hello-jni' library on application * startup. The library has already been unpacked into * /data/data/com.example.hellojni/lib/libhello-jni.so at * installation time by the package manager. */ static { System.loadLibrary("hello-jni"); } }
6.項目中調用so庫函數stringFromJNI,首先添加引用:
import com.example.hellojni.HelloJni;
再調用代碼:
finalEditText editText =(EditText) findViewById(R.id.editText); HelloJni hj =newHelloJni(); editText.setText(hj.stringFromJNI("this is java!"));
7.打包發布:

8.其他:
ndk默認是不支持c99(c++),如果需要c99,則修改Android.mk文件,添加LOCAL_CFLAGS := -std=c99
LOCAL_CFLAGS := -std=c99