JNI + Android

JNI 사용 구조는 다음 그림으로 요약할 수 있습니다.

Android에서 사용하는데 필요한 것은 5 단계에서 Cross Compiler로 컴파일 되어야 한다는 것입니다.

그리고 컴파일 된 결과가 “.DLL”이 아니라 “.so” 파일로 나온다는 거겠죠.

Cross Compiler는 http://www.codesourcery.com/gnu_toolchains/arm/download.html 에서 구할 수 있습니다.

그런데 gcc의 -shared 옵션으로 .so 파일을 만들고 실행해보면, 사용될 때 App가 죽어버립니다.

이는 precompiled-library에 관련된 문제로 보이는데, 이를 위해서 컴파일 단계의 ldscript를 수정해서 사용합니다.

http://honeypod.blogspot.com/2007/12/shared-library-hello-world-for-android.html 를 참고하면 다음과 같은 부분을 볼 수 있습니다.

Now, the default linker script need to be modified. The default
linker script is available at
$toolchains_home/arm-none-linux-gnueabi/lib/ldscripts/armelf_linux_eabi.xsc.
Copy it to the current directory. Comment out three lines and add one
line replacing the first commented out line.

/* . = ALIGN (CONSTANT (MAXPAGESIZE)) – ((CONSTANT (MAXPAGESIZE) – .) & (CONSTANT (MAXPAGESIZE) – 1)); . = DATA_SEGMENT_ALIGN (CONSTANT (MAXPAGESIZE), CONSTANT (COMMONPAGESIZE)); */
. = .; /* this line replaces the line above */

/* . = DATA_SEGMENT_RELRO_END (0, .); */

/* . = DATA_SEGMENT_END (.); */

$toolchains_home/arm-none-linux-gnueabi/lib/ldscripts/ 경로에 있는 armelf_linux_eabi.xsc 파일을 수정해야 한다는 이야기입니다.

수정한 파일을 사용해서 다음 명령으로 컴파일하면 실제 안드로이드에서 동작하는 라이브러리를 만들 수 있습니다.

arm-none-linux-gnueabi-gcc -I/usr/lib/jvm/java-6-sun/include -I/usr/lib/jvm/java-6-sun/include/linux -fpic -c <JNI 함수 구현소스>.c

arm-none-linux-gnueabi-ld -T armelf_linux_eabi.xsc -shared -o <library명>.so <Object파일>.o

그리고 emulator 실행 후 다음 명령으로 에뮬레이터에서 실행가능합니다.

adb push <라이브러리>.so /system/lib
adb install <JNI를 사용하는 Android APP>.apk

구글 Android SDK 셋팅(우분투 8.04 기준)

1. http://code.google.com/android 에서 Download the SDK 를 클릭

2. 라이센스 확인

3. Linux (i386) 용 zip 다운로드

4. 압축 해제.

4.1. 계정의 .profile 맨 마지막에 다음 내용을 추가하고 다시 로그인 << 여기 추가되었습니다.

PATH=”$HOME/android/tools:$PATH”
PATH=”$HOME/eclipse/tools:$PATH”

4.2. 압축해제한 디렉토리를 ~/android 로 symbolic link. << 여기 추가되었습니다.

5. JDK 설치(sudo apt-get install sun-java6-jdk)

6. http://code.google.com/android 의 Docs 를 눌러 Getting started / Installing the SDK

7. System and Software Requirements 의 Eclipse 를 눌러 Eclipse IDE for Java Developers를 다운로드

8. 홈폴더에서 압축해제.

[#M_* 바탕화면에서 실행하기 위해 $HOME/바탕화면/eclipse.desktop 생성|<<접기>>| [Desktop Entry]
Version=1.0
Exec=/home/dasomoli/eclipse/eclipse
Icon=/home/dasomoli/eclipse/icon.xpm
Name=Eclipse
GenericName=Development Tools
Comment=Eclipse
Encoding=UTF-8
Terminal=false
Type=Application
Categories=Application;Development;_M#]
9. Eclipse에서 WST 설치

10. Eclipse에서 https://dl-ssl.google.com/android/eclipse/ 를 추가하고 설치

11. Eclipse에서 Window/Preference 의 Android 의 SDK Location 을 아까 SDK의 압축 해제 디렉토리로 지정

12. 프로젝트 시작!