Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JNI loading : Warning : Do not hardcode use Context.getFilesDir().getPath() instead

I am facing a problem in one of my app, I have the following code to load a lib (JNI) the app needs :

static {
    // load the JNI library
    Log.i("JNI", "loading JNI library...");
    System.load("/data/data/com.mypackage.appname/lib/libxxxxxx.so");
    Log.i("JNI", "JNI library loaded!");
}

So i get get the warning : "Do note hardcode use Context.getFilesDir().getPath() instead" which is totally rightful (It's not going to be portable on every devices). The thing is, because I am using static I can't call for Context.getFilesDir().getPath().

Do you have any ideas on how I can proceeded to do it ?

like image 700
Joze Avatar asked Mar 05 '13 09:03

Joze


2 Answers

your warning is absolutely clear, try the following way instead:

make the following class:

public class MyApplication extends Application {
    private static Context c;

    @Override
    public void onCreate(){
        super.onCreate();

        this.c = getApplicationContext();
    }

    public static Context getAppContext() {
        return this.c;
    }
}

declare the above class in your android manifest:

<application android:name="com.xyz.MyApplication"></application>

And then

static {
    // load the JNI library
    Log.i("JNI", "loading JNI library...");

    System.load(MyApplication.getAppContext().getFilesDir().getParentFile().getPath() + "/lib/libxxxxxx.so");

    Log.i("JNI", "JNI library loaded!");
}

P.S not tested

like image 116
NullPointer Avatar answered Oct 24 '22 04:10

NullPointer


You can get Context from your class derived from Application. take a look into example So you can use your application context everywhere:)

like image 26
Taras Avatar answered Oct 24 '22 03:10

Taras