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

          最近在研究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文件:

http://download.csdn.net/detail/coder80/5071729

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值