Coder80的专栏

最近在研究JNI编程,顺便实现了一个小demo,使用native递归的方法,遍历手机sd卡目录的mp3文件,在JNI层,输出MP3文件的绝对路径。在执行效率上,,与Java实现方式进行比对,确实native层的C代码明显好很多。

此demo比较简单,复杂之处在于C函数的实现。由于长期从事Java开发,导致C语言的东西都遗忘不少。

void Java_com_coder80_scaner1_MainActivity_scanDir(JNIEnv *env, jobject obj, jstring jdirPath){const char *path = (*env)->GetStringUTFChars(env,jdirPath,NULL);LOGE("begin to call scan_dir() in the JNI,and path = %s \n",path);scan_dir(path);}void scan_dir(const char *directory){DIR *dp;struct dirent *entry;struct stat statbuf;if((dp = opendir(directory)) == NULL){perror("opendir");return;}chdir(directory);//LOGE("pyb chdir directory = %s\n",directory);while ((entry = readdir(dp)) != NULL) {stat(entry->d_name, &statbuf);if (S_ISDIR(statbuf.st_mode)) {if ((strcmp(entry->d_name, ".") != 0)&& (strcmp(entry->d_name, "..") != 0)&& (entry->d_name[0] != ‘.’)) {scan_dir(entry->d_name);}} else {int size = strlen(entry->d_name);if (entry->d_name[0] != ‘.’&& (statbuf.st_size/1024) > 300 //大于300k,表示肯能有mp3文件(忽略 <300k的mp3)&& strcmp(entry->d_name + (size – 4), ".mp3") == 0){//LOGE("scan_dir(),file st_size = %d \n\n",(statbuf.st_size/1024));char* parentPath = (char*)malloc(1024);char* absolutePath = (char*)malloc(1024);//首先获取工作路径getcwd(parentPath,1024);//LOGE("parentPath = %s \n", parentPath);strcpy(absolutePath,parentPath);char *p = "/";absolutePath = strcat(absolutePath,p);absolutePath = strcat(absolutePath,entry->d_name);//statbuf.st_size,LOGE("scan_dir(),file absolutePath = %s \n", absolutePath);free(parentPath);parentPath = NULL;free(absolutePath);absolutePath = NULL;}}}chdir("..");closedir(dp);}

此demo虽说可以比对native与Java执行的效率,但是代码中native函数效率依然较低。市面上一些音乐播放器,例如酷狗和多米音乐,他们app中就有扫描sd卡音频文件的功能,其执行速度比我demo中要快很多,效率为我demo中的5倍左右。

博客中已经将代码上传,扫描sd卡中MP3的效率确实存在问题,如何能够提升代码执行效率,目前没有好的思路。各位大侠,如果有好的建议,不妨提供一下思路,先谢谢!

Android JNI层实现扫描sd卡mp3文件:

三人一条心,黄土变成金。

Coder80的专栏

相关文章:

你感兴趣的文章:

标签云: