从Android Studio 2.2以后,原生代码更倾向于使用CMake(CMakeLists.txt)来编译,而不是Android.mk(但也一直支持,不过不允许混用)。参考:Android.mk转换成CMakeLists.txt
Android的工程可以在命令行下编译:
工程目录> ./gradlew assembleDebug
默认环境已内置LLDB,可以直接对C++文件进行断点调试。需要先以Debug App模式启动,然后在应用等待调试进程连接的时候,点击Attch Debuger to Android Process.
在Android Studio里打开apk文件,可以看到里面的内容,可以查看某些资源文件是否被正确打包进去了。
a. 编译libsndfile库
源代码:https://github.com/libsndfile/libsndfile(这个交叉编译有错,对mp3lame有依赖,不能用),要用以前官网的稳定版1.0.28:http://www.mega-nerd.com/libsndfile/
a.1 构建toolchain
ndk自带了toolchain:~/Library/Android/sdk/ndk/21.2.6472646/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64/bin
NDKr19之前需要自己编译toolchain:
~/code/ndk-21.2.6472646$ build/tools/make-standalone-toolchain.sh --toolchain=arm-linux-androideabi-4.9 --platform=android-30 --install-dir=../ndk-toolchain-21.2.6472646
HOST_OS=darwin
HOST_EXE=
HOST_ARCH=x86_64
HOST_TAG=darwin-x86_64
HOST_NUM_CPUS=4
BUILD_NUM_CPUS=8
Auto-config: --arch=arm
Toolchain installed to ../ndk-toolchain-21.2.6472646.
a.2 编译
libsndfile里有个Android编译说明,但是已经过时不能用了。
export NDK=~/Library/Android/sdk/ndk/21.2.6472646
export TOOLCHAIN=$NDK/toolchains/llvm/prebuilt/darwin-x86_64
export TARGET=armv7a-linux-androideabi
export API=21
export AR=$TOOLCHAIN/bin/llvm-ar
export CC=$TOOLCHAIN/bin/$TARGET$API-clang
export AS=$CC
export CXX=$TOOLCHAIN/bin/$TARGET$API-clang++
export LD=$TOOLCHAIN/bin/ld
export RANLIB=$TOOLCHAIN/bin/llvm-ranlib
export STRIP=$TOOLCHAIN/bin/llvm-strip
export TOOLCHAIN=$NDK/toolchains/llvm/prebuilt/darwin-x86_64
brew install autogen
./autogen.sh
./configure --prefix=/opt/android --host=$TARGET --enable-static --enable-shared=no --disable-mpeg
make
cp src/.libs/libsndfile.a libs/armeabi-v7a/
不同芯片架构交叉编译参数映射如下:
armeabi-v7a
=> export TARGET=armv7a-linux-androideabiarm64-v8a
=>export TARGET=aarch64-linux-android
x86
=>export TARGET=i686-linux-android
x86_64
=>export TARGET=x86_64-linux-android
参考:
HOWTO Cross compiling on Android
b. Android文件权限问题(这个问题浪费了我半天时间!)
Google has a new feature on Android Q: filtered view for external storage. A quick fix for that is to add this code in the AndroidManifest.xml file:
<manifest ... > <!-- This attribute is "false" by default on apps targeting Android Q. --> <application android:requestLegacyExternalStorage="true" ... > ... </application> </manifest>
You can read more about it here: https://developer.android.com/training/data-storage/compatibility
评论