Creating temporary files in Android with NDK
The best way we've found is to call Context.getCacheDir
on startup, get its path with getAbsolutePath
, then call a JNI function to store that path in a global. Any function that wants to create a temporary file simply appends a suitable temporary file name to that path.
If you really want to fetch it from JNI another alternative would be to pass in a Context
to a JNI function and use a bunch of GetMethodID
/ CallObjectMethod
stuff to call back into Java to getCacheDir
, but the former approach is a lot simpler.
Unfortunately, there does not appear to be a more elegant solution at the moment.
Below is the GetMethodID / CallObjectMethod procedure that Ertebolle refers to. It is necessary if you are working with a pure native app (such as built by Visual Studio 2015) and cannot use java code.
std::string android_temp_folder( struct android_app *app ) {
JNIEnv* env;
app->activity->vm->AttachCurrentThread( &env, NULL );
jclass activityClass = env->FindClass( "android/app/NativeActivity" );
jmethodID getCacheDir = env->GetMethodID( activityClass, "getCacheDir", "()Ljava/io/File;" );
jobject cache_dir = env->CallObjectMethod( app->activity->clazz, getCacheDir );
jclass fileClass = env->FindClass( "java/io/File" );
jmethodID getPath = env->GetMethodID( fileClass, "getPath", "()Ljava/lang/String;" );
jstring path_string = (jstring)env->CallObjectMethod( cache_dir, getPath );
const char *path_chars = env->GetStringUTFChars( path_string, NULL );
std::string temp_folder( path_chars );
env->ReleaseStringUTFChars( path_string, path_chars );
app->activity->vm->DetachCurrentThread();
return temp_folder;
}