1. 在assets目录中添加文件log.txt,里面随便写点什么,hello,world好了
2. 在 HelloJni.java中
public void onCreate(Bundle savedInstanceState)
3. 在hello-jni.c中,添加实现-
{
-
nativeReadFromAssets(getAssets(),"log.txt"); //onCreate中添加调用
-
}
- public native void nativeReadFromAssets(AssetManager ass,String filename); //声明
-
/*******************************************************************************
-
* Function Name : java_com_fontlose_ReadAssets_readFromAssets
-
* Description : 定义:public native void readFromAssets(AssetManager ass,String filename);
-
* Input : AssetManager 对象 filename资源名
-
* Output : None
-
* Return : None
-
*******************************************************************************/
-
void Java_com_example_hellojni_HelloJni_nativeReadFromAssets(JNIEnv* env,jclass tis,jobject assetManager,jstring filename)
-
{
-
LOGI("ReadAssets");
-
AAssetManager* mgr = AAssetManager_fromJava(env, assetManager);
-
if(mgr==NULL)
-
{
-
LOGI(" %s","AAssetManager==NULL");
-
return ;
-
}
-
-
/*获取文件名并打开*/
-
jboolean iscopy;
-
const char *mfile = (*env)->GetStringUTFChars(env, filename, &iscopy);
-
AAsset* asset = AAssetManager_open(mgr, mfile,AASSET_MODE_UNKNOWN);
-
(*env)->ReleaseStringUTFChars(env, filename, mfile);
-
if(asset==NULL)
-
{
-
LOGI(" %s","asset==NULL");
-
return ;
-
}
-
/*获取文件大小*/
-
off_t bufferSize = AAsset_getLength(asset);
-
LOGI("file size : %d\n",bufferSize);
-
char *buffer=(char *)malloc(bufferSize+1);
-
buffer[bufferSize]=0;
-
int numBytesRead = AAsset_read(asset, buffer, bufferSize);
-
LOGI(": %s",buffer);
-
free(buffer);
-
/*关闭文件*/
-
AAsset_close(asset);
- }
-
#include <jni.h>
-
#include <android/asset_manager.h>
-
#include <android/asset_manager_jni.h>
-
#include <android/log.h>
-
-
#define TAG "HELLO"
-
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__)
-
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG , TAG, __VA_ARGS__)
-
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO , TAG, __VA_ARGS__)
-
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN , TAG, __VA_ARGS__)
- #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR , TAG, __VA_ARGS__)
-
LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog
- LOCAL_LDLIBS += -landroid
[参]