Android ndk下用AssetManager讀取assets的資源

來源:互聯網
上載者:User

標籤:android   style   blog   class   code   java   

轉自:http://www.cppblog.com/johndragon/archive/2012/12/28/196754.html

在使用 cocos2dx 在 Android 上進行遊戲開發時,遇到了奇怪的事情,無論什麼代碼,都無法讀資源檔。不得以只好尋求更高版本的Api。 

在Android ndk api level 9 之後,提供了一套稱為 AssetManager 的api。

這個api 的工作原理是    - Java通過JNI把getAssets得到的AssetManager傳遞給一個JNI的c函數。   - JNI的c函數通過 AAssetManager_fromJava 來取到這個AssetManager對象。   - 通過一系列的 AssetManager 的api來操作Assets。 C的jni函數如下
static AAssetManager * gAssetMgr = NULL;extern "C"{  void Java_org_cocos2dx_lib_Cocos2dxActivity_nativeSetAssetManager(JNIEnv* env, jclass cls, jobject assetManager)  {     gAssetMgr = AAssetManager_fromJava( env, assetManager );  }};

讀取資源的方法如下

do{    AAsset * pAsset = AAssetManager_open(gAssetMgr, pszFileName, AASSET_MODE_UNKNOWN);    if( pAsset == NULL ) break;         size_t size = AAsset_getLength(pAsset);         if( size > 0 )         {             pData = new unsigned char[size];             int iRet = AAsset_read( pAsset, pData, size);             if( iRet <= 0 )             {                 delete [] pData;                 pData = NULL;             }         }         AAsset_close(pAsset);         if( pAsset == NULL ) size = 0;         if( pSize )             *pSize = size;} while(0);
這裡修改的是cocos2dx的CCFileUtils_Android.cpp 中的getFileData 函數。 最後,在編譯libgame.so 時,要注意在Android.mk裡的LD參數裡加上-landroid來串連有關的庫。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.