6

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 ?

Avadhani Y
  • 7,566
  • 19
  • 63
  • 90
Joze
  • 1,285
  • 4
  • 19
  • 33
  • You get the warning from what? – user207421 Mar 05 '13 at 09:18
  • In system.Load I get : Do not hardcode "/data/"; use Context.getFilesDir().getPath() instead – Joze Mar 05 '13 at 09:23
  • Arrived here due to the lint warning saying the same in Eclipse. Spotted this post, which if correct, is a little worrying: https://code.google.com/p/android/issues/detail?id=43533 – brandall Mar 05 '13 at 20:32
  • You would normally accomplish this using System.loadLibrary() which takes only the name of the library without path, lib prefix, or .so extension (all of which are automatically filled in as appropriate for the platform in use) – Chris Stratton May 19 '13 at 18:08

2 Answers2

12

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

Ali
  • 2,012
  • 3
  • 25
  • 41
  • Thanks for your answer but I get : Cannot make a static reference to the non-static method getFilesDir() from the type Context – Joze Mar 05 '13 at 09:21
  • Just tried it but I get : /data/data/com.mypackage.appname/files instead of what I need : /data/data/com.mypackage.appname/ (no files). Any guesses ? – Joze Mar 05 '13 at 09:56
  • Works perfectly. Thanks a lot ! Validated + "+1" ;) – Joze Mar 05 '13 at 10:11
1

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

Community
  • 1
  • 1
Taras
  • 2,526
  • 3
  • 33
  • 63