cocos2dx 实现obb包读取 quick2.2.6


实现方式:

  1. 这个方案没有采用google 的jobb 方式打包obb而是通过zip包的方式进行打包obb
  2. 在android部分获取Sound, Music,Video 时是通过 AssetFileDescriptor 进行读取的所以 通过设置 android 中的反射 addAssetPath 进行添加路径 下面代码会有用到注意查看
  3. cocos 方面修改部分c++ 代码让cocos能够读取到obb包中的内容
  4. obb包直接通过winrar 进行打包 这里注意 压缩时选择zip格式,压缩方式选择->存储
    5.https://pan.baidu.com/s/1i507k5f zip读取类 google 官方库

obb打包方式

打包完毕文件后缀名 zip 修改obb (obb 命名方式 mian.versionCode.packageName.obb 注意:assets目录为根目录)


以下为代码实现 不要直接复制只是把需要修改的地方进行说明 根据自己情况进行修改

当前使用版本为2.x

3.x版本的应该大同小异自己修改下对应的地方就行了

1.获取obb包路径在项目的 MainActivity.java(这个文件可能名字不一样 继承于 Cocos2dxActivity)


public static String FATE_OBB_PATH= "";
public void onCreate(Bundle savedInstanceState) {
    //获取obb 路径
    FATE_OBB_PATH =getVirtualObbFileFullpath() ;//这句需要放在super.onCreate上面
    super.onCreate(savedInstanceState);
    ...
}

public String getObbFileName() {  
    PackageInfo info = null;  
    try {
        info = super.getPackageManager().getPackageInfo(super.getPackageName(), 0);
        String fileName = "main." + info.versionCode + "." + getPackageName() + ".obb";
        
        return fileName;
} catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return "";
}
public String getVirtualObbFileFullpath(){
    File sdcardDir = Environment.getExternalStorageDirectory();
    String _path = getObbDir().getPath() + "/" + getObbFileName();
    Log.e("===_path===", _path);
    return _path;
}

2. Cocos2dxHelper 代码修改


    public static ZipResourceFile obbzip = null;

    public static void init(final Context pContext, final Cocos2dxHelperListener pCocos2dxHelperListener) {
        ...
        // begin--------------------添加代码----------------------------
        //检查obb文件是否存在
        if(fileIsExists(MainActivity.FATE_OBB_PATH)){
            //存在添加obb路径到cocos中 注意 nativeSetObbPath 方法是需要新添加的 下方会介绍
            Cocos2dxHelper.nativeSetObbPath(MainActivity.FATE_OBB_PATH);
        }
        // end--------------------添加代码----------------------------

        Cocos2dxHelper.nativeSetApkPath(applicationInfo.sourceDir);
        Cocos2dxHelper.sCocos2dxAccelerometer = new Cocos2dxAccelerometer(pContext);
        Cocos2dxHelper.sCocos2dMusic = new Cocos2dxMusic(pContext);
        int simultaneousStreams = Cocos2dxSound.MAX_SIMULTANEOUS_STREAMS_DEFAULT;
        if (Cocos2dxHelper.getDeviceModel().indexOf("GT-I9100") != -1) {
            simultaneousStreams = Cocos2dxSound.MAX_SIMULTANEOUS_STREAMS_I9100;
        }
        Cocos2dxHelper.sCocos2dSound = new Cocos2dxSound(pContext, simultaneousStreams);
        Cocos2dxHelper.sAssetManager = pContext.getAssets();
        //设置压缩包
        PackageInfo info = null;
        try {
            info = pContext.getPackageManager().getPackageInfo(pContext.getPackageName(), 0);
            Cocos2dxHelper.obbzip = APKExpansionSupport.getAPKExpansionZipFile(pContext,info.versionCode,0);
        } catch (PackageManager.NameNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        // end--------------------添加代码----------------------------
        PSNetwork.init(pContext);
        Cocos2dxBitmap.setContext(pContext);
        Cocos2dxETCLoader.setContext(pContext);
    }
    //检查obb文件是否存在
    public static boolean fileIsExists(String strFile)
    {
        try
        {
            File f=new File(strFile);
            if(!f.exists())
            {
                return false;
            }

        }
        catch (Exception e)
        {
            return false;
        }

        return true;
    }

    private static native void nativeSetApkPath(final String pApkPath);
    //nativeSetObbPath 设置obb路径方法
    private static native void nativeSetObbPath(final String pObbPath);

3. 修改 Cocos2dxMusic.java 和 Cocos2dxSound.java 将获得AssetFileDescriptor的地方加入obb包查找


//Cocos2dxMusic.java
final AssetFileDescriptor assetFileDescritor =  Cocos2dxHelper.obbzip.getAssetFileDescriptor("assets/"+pPath);
if(assetFileDescritor == null) {
    final AssetFileDescriptor assetFileDescritor1 = this.mContext.getAssets().openFd(pPath);
    mediaPlayer.setDataSource(assetFileDescritor1.getFileDescriptor(), assetFileDescritor1.getStartOffset(), assetFileDescritor1.getLength());
}else{
    mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength());
}
//Cocos2dxSound.java
final AssetFileDescriptor assetFileDescritor =  Cocos2dxHelper.obbzip.getAssetFileDescriptor("assets/"+pPath);
if(assetFileDescritor == null) {
    final AssetFileDescriptor assetFileDescritor1 = this.mContext.getAssets().openFd(pPath);
    soundID = this.mSoundPool.load(assetFileDescritor1, 0);
}else{
    soundID = this.mSoundPool.load(assetFileDescritor, 0);

}

4. 修改 Java_org_cocos2dx_lib_Cocos2dxHelper.cpp


string g_apkPath;
//添加obb path
string g_obbPath;
//添加设置obbpath 方法
 JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetObbPath(JNIEnv*  env, jobject thiz, jstring obbPath) {
    g_obbPath = JniHelper::jstring2string(obbPath);
}
//添加获取obbpath 方法
const char * getObbPath() {
    return g_obbPath.c_str();
}

5.修改 CCFileUtilsAndroid.h


//添加方法
extern const char * getObbPath();

6.修改 CCFileUtilsAndroid.cpp


static ZipFile *s_pZipFile = NULL;
//在 s_pZipFile 下添加一个 obb zip包解析
static ZipFile *s_pZipFileobb = NULL;

//在sharedFileUtils() 中创建obb的zip
CCFileUtils* CCFileUtils::sharedFileUtils()
{
    if (s_sharedFileUtils == NULL)
    {
        s_sharedFileUtils = new CCFileUtilsAndroid();
        s_sharedFileUtils->init();
        std::string resourcePath = getApkPath();
        s_pZipFile = new ZipFile(resourcePath, "assets/");
        // begin ------------------代码添加
        //获取obb路径
        std::string resourcePath_Obb = getObbPath();
        //  创建obbzip
        s_pZipFileobb = new ZipFile(resourcePath_Obb,"assets/");
        // end --------------------代码添加

    }
    return s_sharedFileUtils;
}
CCFileUtilsAndroid::~CCFileUtilsAndroid()
{
    CC_SAFE_DELETE(s_pZipFile);
    //销毁
    CC_SAFE_DELETE(s_pZipFileobb);
}

//文件检查中的修改
bool CCFileUtilsAndroid::isFileExist(const std::string& strFilePath)
{
    if (0 == strFilePath.length())
    {
        return false;
    }

    bool bFound = false;
    
    // Check whether file exists in apk.
    if (strFilePath[0] != '/')
    {
        std::string strPath = strFilePath;
        if (strPath.find(m_strDefaultResRootPath) != 0)
        {// Didn't find "assets/" at the beginning of the path, adding it.
            strPath.insert(0, m_strDefaultResRootPath);
        }
        if (s_pZipFile->fileExists(strPath))
        {
            bFound = true;
        } 
        // begin -------------代码添加
        if(!bFound){
           
            if (s_pZipFileobb->fileExists(strPath))
            {
                
                bFound = true;
            } 
        }
        // end -----------------代码添加
    }
    else
    {
        FILE *fp = fopen(strFilePath.c_str(), "r");
        if(fp)
        {
            bFound = true;
            fclose(fp);
        }
    }
    return bFound;
}


//文件获取方法中的代码修改
unsigned char* CCFileUtilsAndroid::doGetFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize, bool forAsync)
{
    unsigned char * pData = 0;
    
    if ((! pszFileName) || (! pszMode) || 0 == strlen(pszFileName))
    {
        return 0;
    }
    
    string fullPath = fullPathForFilename(pszFileName);
    
    if (fullPath[0] != '/')
    {
        if (forAsync)
        {
            pData = s_pZipFile->getFileData(fullPath.c_str(), pSize, s_pZipFile->_dataThread);
            // begin -------------代码添加
            if (! pData)
            {
                pData = s_pZipFileobb->getFileData(fullPath.c_str(), pSize, s_pZipFile->_dataThread);
            }
            //end -------------代码添加
        }
        else
        {
            pData = s_pZipFile->getFileData(fullPath.c_str(), pSize);
            // begin -------------代码添加
            if (! pData)
            {
                pData = s_pZipFileobb->getFileData(fullPath.c_str(), pSize);
            }
            //end -------------代码添加
        }
    }
    else
    {
        do
        {
            // read rrom other path than user set it
            //CCLOG("GETTING FILE ABSOLUTE DATA: %s", pszFileName);
            FILE *fp = fopen(fullPath.c_str(), pszMode);
            CC_BREAK_IF(!fp);
            
            unsigned long size;
            fseek(fp,0,SEEK_END);
            size = ftell(fp);
            fseek(fp,0,SEEK_SET);
            pData = new unsigned char[size];
            size = fread(pData,sizeof(unsigned char), size,fp);
            fclose(fp);
            
            if (pSize)
            {
                *pSize = size;
            }
        } while (0);
    }
    
    if (! pData)
    {
        std::string msg = "Get data from file(";
        msg.append(pszFileName).append(") failed!");
        CCLOG("%s", msg.c_str());
    }
    
    return pData;
}

测试:

  1. Root手机
  2. 安装 re文件管理器
  3. re文件管理器
  4. 挂载为可读写
  5. 挂载为可读写
  6. 上传obb包
    1. 检查是否有 对应目录 /storage/emulated/0/Android/obb/com.k0204.game/ 如果没有自己创建一下
    2. adb push E:\main.5.com.k0204.game.obb /storage/emulated/0/Android/obb/com.k0204.game/
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,902评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,037评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,978评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,867评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,763评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,104评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,565评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,236评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,379评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,313评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,363评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,034评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,637评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,719评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,952评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,371评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,948评论 2 341

推荐阅读更多精彩内容