前端之家收集整理的这篇文章主要介绍了
Cocos2.2.3在线下载——sd卡容量判定,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
文介绍的是在线下载时如何判断sd卡的容量是否足够,分为三步:
1.getPackageSize()——获取URL包的大小
2.getSdcardSize()——获取sd的剩余容量
3.isSizeEnough()——判断sd的容量是否足够
#include <curl/curl.h>
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "JniHelper.h"
#endif
//在线下载时,获取要下载的包的大小
//引用自http://www.cnblogs.com/JD85/p/3914949.html
float DLManager::getPackageSize()
{
//获取资源包大小——单位为MB
float packageSize = 0;
double zipsize = 0;
CURL *handle = curl_easy_init();
curl_easy_setopt(handle,CURLOPT_URL,_packageUrl.c_str());
curl_easy_setopt(handle,CURLOPT_HEADER,1); //只需要header头
curl_easy_setopt(handle,CURLOPT_NOBODY,1); //不需要body
if (curl_easy_perform(handle) == CURLE_OK)
{
curl_easy_getinfo(handle,CURLINFO_CONTENT_LENGTH_DOWNLOAD,&zipsize);
float packageBytesTotal = (zipsize / 1024.f / 1024.f);
CCLog("Package Size: %.2f MB",packageBytesTotal);
packageSize = packageBytesTotal;
}
curl_easy_cleanup(handle);
return packageSize;
}
//获取sd卡容量————C++
//通过jni来获取sd卡剩余容量
float DLManager::getSdcardSize()
{
std::string m_mainActivityName = XtcUtils::xtcGetMainActivityName();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
JniMethodInfo methodInfo;
jfloat ret = 0.f;
if (JniHelper::getStaticMethodInfo(methodInfo,m_mainActivityName.c_str(),"readSDCard","()F"))
{
ret = methodInfo.env->CallStaticFloatMethod(methodInfo.classID,methodInfo.methodID);
return ret;
}
return 0;
#endif
//win32下直接返回一个大容量
return 5096;
}
//获取sd卡容量————Android
//将下列代码贴入proj.android\src\com\xtc\xx\xx.java
//引用自http://blog.csdn.net/zhaoweixing1989/article/details/7364362
public static float readSDCard() {
float ret = 0.f;
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)) {
File sdcardDir = Environment.getExternalStorageDirectory();
StatFs sf = new StatFs(sdcardDir.getPath());
long blockSize = sf.getBlockSize();
long blockCount = sf.getBlockCount();
long availCount = sf.getAvailableBlocks();
Log.d("","block大小:"+ blockSize+",block数目:"+ blockCount+",总大小:"+blockSize*blockCount/1024+"KB");
Log.d("","可用的block数目::"+ availCount+",剩余空间:"+ availCount*blockSize/1024+"KB");
//单位为MB
ret = availCount*blockSize/1024/1024;
}
return ret;
}
//判断sd卡是否有足够容量存储在线下载的包
bool DLManager::isSizeEnough()
{
bool bRet = false;
float sdcardSize = getSdcardSize();
float packageSize = getPackageSize();
//判断文件类型
string suffix;
int pos = getPackageUrl().find_last_of("."); //getPackageUrl()为服务器上包的路径,ex.http://192.168.100.11/AssociativeVideo/A.zip
suffix = getPackageUrl().substr(pos,getPackageUrl().length() - 1);
if(suffix.compare(".zip") == 0)
{//若为zip文件,需将包大小设置为解压时的最大大小
packageSize = packageSize * 2 + 0.5f;
}
if(sdcardSize > packageSize)
{
bRet = true;
}
else
{
CCLog("sdcardSize : %f MB < packageSize : %f MB",sdcardSize/1024.f,packageSize/1024.f);
}
return bRet;
}