Wednesday, August 04, 2010

HACK: Adding JAR & JNI Libraries to a NBAndroid Project

In general, the Android Plugin for Netbeans (NBAndroid) is a great alternative to the the official ADT Plugin for Eclipse provided by Google. However, as of the timing writing it has two annoying bugs: it does neither support Java nor native libraries to be installed with the application package (.apk) on the phone. Fortunately, there is an easy workaround for both:

1. Java Libraries

Actually, this already works partly as adding .jar files using the GUI allows compilation of dependent code. The problem is that the contained .class files are not converted and bundled. The result is a ClassNotFoundException when running the application. Overriding the "-dex" target in the build.xml does the job:

<target depends="init,compile,-pre-pre-jar,-pre-jar" name="-dex">
    <pathconvert pathsep=" " property="javac.classpath.with.spaces">
        <path path="${javac.classpath}"/>
    </pathconvert>
    <exec executable="${dx}" failonerror="true">
        <arg value="--dex"/>
        <arg value="--output=${basedir}/${intermediate.dex}"/>
        <arg value="--positions=lines"/>
        <arg file="${build.classes.dir}"/>
        <arg line="${javac.classpath.with.spaces}"/>
    </exec>
</target>
Source: This workaround is actually a re-post of Andrey Moiseev's comment on the bug report.

2. Native Libraries

Native libraries are usually found below an optional libs folder in the project directory, e.g. "libs/armeabi/libFoo.so". While some build scripts automatically add the contents to the .apk file, the one generated by the NBAndroid plug-in unfortunately does not. Again the solution is overriding a target by adding the following to the build.xml (requries an exisiting libs directory).

<target depends="init,-package-res-and-assets,-package-res-no-assets,-package-dex" name="-sign">
    <exec executable="${apkbuilder}" failonerror="true">
        <arg value="${basedir}/${dist.apk}"/>
        <arg value="-z"/>
        <arg value="${basedir}/${dist.apk}_"/>
        <arg value="-nf"/>
        <arg value="${basedir}/libs"/>
    </exec>
    <delete file="${dist.apk}_"/>
</target>

No comments: