android 如何加载ndk,如何将文件添加到Android项目,然后使用NDK加载它

有两种选择,它取决于您的目标.

如果您的文件是基本文本配置文件,则可以使用这两种情况,但如果您的文件是(.obj,.max,.dae)等3D对象,则应使用AssetManager类.

第一个选项:(以res raw格式存储文件(可以使用fopen())).

>在res目录中创建一个名为raw的文件夹(res-> raw).

>将您的文件写入apk私人目录.

在Java中:

public void writeFileToPrivateStorage(int fromFile, String toFile)

{

InputStream is = mContext.getResources().openRawResource(fromFile);

int bytes_read;

byte[] buffer = new byte[4096];

try

{

FileOutputStream fos = mContext.openFileOutput(toFile, Context.MODE_PRIVATE);

while ((bytes_read = is.read(buffer)) != -1)

fos.write(buffer, 0, bytes_read); // write

fos.close();

is.close();

}

catch (FileNotFoundException e)

{

e.printStackTrace();

}

catch (IOException e)

{

e.printStackTrace();

}

}

然后,调用您的函数:

writeFileToPrivateStorage(R.raw.your_file,"your_output_file.txt");

>获取私人路径

path=mContext.getApplicationContext().getFilesDir().toString();

>在Java中定义您的JNI函数:

public static native void setconfiguration(String yourpath);

>用C/C++实现:

JNIEXPORT void JNICALL Java_com_android_gl2jni_GL2JNILib_setconfiguration(JNIEnv * env, jobject obj, jstring path)

{

//convert your string into std::string.

const char *nativeString = env->GetStringUTFChars(config_path, 0);

//make here your fopen.

fopen(nativeString,"r");

}

第二个选项(使用assetManager,通常用于opengl资源).

在这种情况下,参数不是目录的路径,即资产管理器.

>将文件存储在资产目录中.

>在C/C++中定义您的本机功能

public static native void yourfunction(AssetManager assetManager);

>在java中调用此函数:

loadYourFile(m_context.getAssets());

>在C/C++中创建您的jni函数

JNIEXPORT void Java_com_android_gl2jni_GL2JNILib_(JNIEnv * env, jobject obj,jobject java_asset_manager)

{

AAssetManager* mgr = AAssetManager_fromJava(env,java_asset_manager);

AAsset* asset = AAssetManager_open(mgr, (const char *) js, AASSET_MODE_UNKNOWN);

if (NULL == asset) {

__android_log_print(ANDROID_LOG_ERROR, NF_LOG_TAG, "_ASSET_NOT_FOUND_");

return JNI_FALSE;

}

long size = AAsset_getLength(asset);

char* buffer = (char*) malloc (sizeof(char)*size);

AAsset_read (asset,buffer,size);

__android_log_print(ANDROID_LOG_ERROR, NF_LOG_TAG, buffer);

AAsset_close(asset);

}

注意:不要忘记在AndroidManifest.xml中添加权限.

注意二:不要忘记添加:

#include

#include

我希望这个答案可以帮到你.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值