std::string JNIHelper::GetExternalFilesDir() { if (activity_ == NULL) { LOGI( "JNIHelper has not been initialized. Call init() to initialize the " "helper"); return std::string(""); } pthread_mutex_lock(&mutex_); // First, try reading from externalFileDir; JNIEnv* env; activity_->vm->AttachCurrentThread(&env, NULL); jstring strPath = GetExternalFilesDirJString(env); const char* path = env->GetStringUTFChars(strPath, NULL); std::string s(path); env->ReleaseStringUTFChars(strPath, path); env->DeleteLocalRef(strPath); activity_->vm->DetachCurrentThread(); pthread_mutex_unlock(&mutex_); return s; }
/* * ReadFile */ bool JNIHelper::ReadFile(const char *fileName, std::vector<uint8_t> *buffer_ref) { if (activity_ == NULL) { LOGI("JNIHelper has not been initialized.Call init() to initialize the " "helper"); return false; } // Lock mutex std::lock_guard<std::mutex> lock(mutex_); // First, try reading from externalFileDir; JNIEnv *env = AttachCurrentThread(); jstring str_path = GetExternalFilesDirJString(env); const char *path = env->GetStringUTFChars(str_path, NULL); std::string s(path); if (fileName[0] != '/') { s.append("/"); } s.append(fileName); std::ifstream f(s.c_str(), std::ios::binary); env->ReleaseStringUTFChars(str_path, path); env->DeleteLocalRef(str_path); activity_->vm->DetachCurrentThread(); if (f) { LOGI("reading:%s", s.c_str()); f.seekg(0, std::ifstream::end); int32_t fileSize = f.tellg(); f.seekg(0, std::ifstream::beg); buffer_ref->reserve(fileSize); buffer_ref->assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()); f.close(); return true; } else { //Fallback to assetManager AAssetManager *assetManager = activity_->assetManager; AAsset *assetFile = AAssetManager_open(assetManager, fileName, AASSET_MODE_BUFFER); if (!assetFile) { return false; } uint8_t *data = (uint8_t *)AAsset_getBuffer(assetFile); int32_t size = AAsset_getLength(assetFile); if (data == NULL) { AAsset_close(assetFile); LOGI("Failed to load:%s", fileName); return false; } buffer_ref->reserve(size); buffer_ref->assign(data, data + size); AAsset_close(assetFile); return true; } }