public class AssetCopyHelper {
static {
System.loadLibrary("asset_copy");
}
public native void copyAssetToDirectory(String assetName, String destPath);
}
c++实现:
#include <jni.h>
#include <android/asset_manager.h>
#include <android/log.h>
#include <stdio.h>
#include <stdlib.h>
#define LOG_TAG "AssetCopyHelper"
#define LOGI(fmt, ...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, fmt, ##__VA_ARGS__)
#define LOGE(fmt, ...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, fmt, ##__VA_ARGS__)
JNIEXPORT void JNICALL
Java_com_example_yourapp_AssetCopyHelper_copyAssetToDirectory(JNIEnv *env, jobject obj, jstring assetName, jstring destPath) {
AAssetManager* assetManager = AAssetManager_fromJava(env, assetManagerObj);
const char* nativeAssetName = env->GetStringUTFChars(assetName, 0);
const char* nativeDestPath = env->GetStringUTFChars(destPath, 0);
AAsset* asset = AAssetManager_open(assetManager, nativeAssetName, AASSET_MODE_BUFFER);
if (asset == NULL) {
LOGE("Could not open asset %s", nativeAssetName);
return;
}
off_t assetLength = AAsset_getLength(asset);
void* assetBuffer = malloc(assetLength);
AAsset_read(asset, assetBuffer, assetLength);
FILE* destFile = fopen(nativeDestPath, "wb");
if (destFile == NULL) {
LOGE("Could not open file %s", nativeDestPath);
free(assetBuffer);
AAsset_close(asset);
return;
}
fwrite(assetBuffer, 1, assetLength, destFile);
fclose(destFile);
free(assetBuffer);
AAsset_close(asset);
env->ReleaseStringUTFChars(assetName, nativeAssetName);
env->ReleaseStringUTFChars(destPath, nativeDestPath);
}
c实现:
JNIEXPORT void JNICALL
Java_com_example_yourapp_AssetCopyHelper_copyAssetToDirectory(JNIEnv *env, jobject obj, jstring assetName, jstring destPath) { {
const char* nativeAssetName = (*env)->GetStringUTFChars(env,assetName, 0);
const char* nativeDestPath = (*env)->GetStringUTFChars(env,destPath, 0);
AAssetManager* asMg = AAssetManager_fromJava(env, assetManager);
AAsset* asset = AAssetManager_open(asMg,assetName,AASSET_MODE_UNKNOWN );
if(asset==NULL)
{
LOGI("%s not found in asset",assetName);
return;
}
FILE* destFile = fopen(nativeDestPath, "wb");
int assetLength = AAsset_getLength(asset);
char *assetBuffer = (char *)malloc(assetLength);
memset(assetBuffer, 0x00, assetLength);
int numBytesRead = AAsset_read(asset, assetBuffer, assetLength);
FILE* destFile = fopen(dexPath, "wb");
if (destFile == NULL) {
LOGE("Could not open file %s", nativeDestPath);
free(assetBuffer);
AAsset_close(asset);
return;
}
fwrite(assetBuffer, 1, assetLength, destFile);
fclose(destFile);
free(assetBuffer);
AAsset_close(asset);
(*env)->ReleaseStringUTFChars(env,assetName, nativeAssetName);
(*env)->ReleaseStringUTFChars(env,destPath, nativeDestPath);
}