您的位置:首页 > 编程语言 > C语言/C++

How to port native (C/C++) library into android.

2008-12-29 13:59 281 查看
Android official documents don’t have supports for writing native (C/C++) applications or libraries on android. But after all, android is a new platform, a lots of useful software are unavailable on android, if developing them from scratch using android Java framework, it will cost us much more time, further more, native functions should have better performance than pure Java applications. so, we will often think about porting existing native shared library to Android.<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

 

First, you have to pass build on android for your native library, write you own Android.mk including $(BUILD_SHARED_LIBRARY).

Second, using Java Api in Android Framework to write the UI for your application, call the native functions in your native library through JNI

 

At last you may encounter a problem about how to publish your software?.

 

All the native libraries come together with android are prelinked into the system.img, they will go to Android phone when the system.img is flashed into phone. This method is suitable for phone manufactures, but if you want to make a single .apk package to let users around the world to download and install, you have to think about put the native shared library into the .apk package. but how to use it in runtime? Here is a workaround method, pack your shared library into the apk as assets and copy the lib out of the package at the first launch time of your application. How to copy? Using AssetManager in Android Framework, see following sample code:

 

 

InputStream instream = getAssets().open( “native lib path in the apk package” );

 if(new File(“new lib path in phone”).exists() == false)

               copyFile(“new lib path in phone”,instream);       

  

If your native lib size is greater than UNCOMPRESS_DATA_MAX( = 1M currently), you will get exception when using instream to read file,  this time you couldn’t use AssetManager any more, instead you could use zip utilities in Java.util.zip, see following sample code:

           ZipFile zip = new ZipFile(APK_PATH);

           ZipEntry zipen = getFileZipEntry(zip,NATIVE_LIBRARY);

           copyFile(li
8b72
bPath, zip.getInputStream(zipen));

Another point, every Java application in android could only write on it’s own private folder, that is /data/data/packagename/, so the only place you could put your native library is here.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息