Question

I want to load third-party jni library in runtime.
I've tried to load directly from sdcard. It expectedly failed.
I've tried to copy library from sdcard to /data/data/app/ and then
System.load(/data/data/app/libjni.so)
It works on HTC HERO, but fails on HTC Legend with Android 2.1. it fails during execution of native code and write to log uninformative stack trace Any other way to do it? Thats the best piece of code, that works at 1.5(HTC Hero), but donot works on 2.1(HTC Legend).

FileInputStream fis = new FileInputStream("/sdcard/libjni.so");
File nf = new File("/data/data/app/libjni.so");
FileOutputStream fos = new FileOutputStream(nf);
byte[] buf = new byte[2048];
int n;
while ((n = fis.read(buf)) > 0)
    fos.write(buf, 0, n);
fis.close();
fos.close();
System.load("/data/data/app/libjni.so");
Was it helpful?

Solution

Android's dynamic loader cannot load executable code from the sdcard's filesystem, because it is marked non-executable and you cannot map executable memory pages from non-executable storage. (In theory you could manually copy the contents into executable anonymous mapped pages, but that's ugly. Versions of android supporting apps on SD mount an executable file systems contained within a file on the sdcard, but a third party app can't write those)

But what you can do is write a library to a writable location in internal storage - not the lib directory to which you don't have write access, but another one found from Context.getDir() or Context.getFilesDir() and then load it using the full path and .so file name using System.load() instead of System.loadLibrary().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top