当前位置:编程学习 > wap >>

JNI实例1---扫描SD卡中mp3文件

         最近在研究JNI编程,顺便实现了一个小demo,使用native递归的方法,遍历手机sd卡目录的mp3文件,在JNI层,输出MP3文件的绝对路径。在执行效率上,与Java实现方式进行比对,确实native层的C代码明显好很多。
    此demo比较简单,复杂之处在于C函数的实现。由于长期从事Java开发,导致C语言的东西都遗忘不少。
                                     
[cpp]  
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倍左右。
补充:移动开发 , 其他 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,