Android資源動態加載思路

cailongwen 8年前發布 | 20K 次閱讀 安卓開發 Android開發 移動開發

在很多Android應用上,都有資源動態加載的功能,比如更換主題皮膚,替換聊天界面背景圖片等。

微信更換聊天窗口背景

以微信為例,當用戶選擇模板時,會先從網絡上下載相應的圖片資源,然后再替換為聊天界面的背景圖片。我們知道,應用中的資源文件,包括圖片,xml文件等,都是在編譯的時候打包好的,那怎樣才能動態加載資源呢?

其實有一個比較簡單的思路,將需要替換的資源文件打包在一個apk文件中,動態下發到本地,然后通過重新構造Resources對象訪問apk中的資源,進行本地的動態替換。主要有以下幾個步驟:

一、指定資源文件加載路徑

Android應用中的資源是通過AssetManager來管理的,其中addAssetPath方法可以指定資源加載路徑。

/** 
  * Add an additional set of assets to the asset manager. This can be 
  * either a directory or ZIP file.  Not for use by applications.  Returns 
  * the cookie of the added asset, or 0 on failure. 
  * {@hide} 
  */
 public final int addAssetPath(String path) {    
     synchronized (this) {        
         int res = addAssetPathNative(path);           
         makeStringBlocks(mStringBlocks);        
         return res;    
     }
 }

很顯然這是個隱藏的API,所以需要通過反射來調用。

private AssetManager createAssetManager(String skinFilePath) {  
    try {        
        AssetManager assetManager = AssetManager.class.newInstance();        
        Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);        
        addAssetPath.invoke(assetManager, skinFilePath);        
        return assetManager;    
    } catch (Exception e) {        
       e.printStackTrace();        
       return null;    
    }
}

二、構造Resources對象

private Resources createResources(Context context, AssetManager assetManager) {    
    Resources superRes = context.getResources();    
    Resources resources = new Resources(assetManager, superRes.getDisplayMetrics(), superRes.getConfiguration());      
    return resources;
}

有了Resource對象,就可以訪問指定路徑的資源文件,進行動態替換,示例如下:

public class SkinManager {
    private Resources mResources;
    /**
     * 獲取APK資源
     * @param context 上下文
     * @param apkPath APK路徑
     */
    public void loadSkinRes(Context context, String skinFilePath) {
        if (TextUtils.isEmpty(skinFilePath)) {
            return ;
        }
        try {
            AssetManager assetManager = createAssetManager(skinFilePath);
            mResources = createResources(context, assetManager);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private AssetManager createAssetManager(String skinFilePath) {
        try {
            AssetManager assetManager = AssetManager.class.newInstance();
            Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
            addAssetPath.invoke(assetManager, skinFilePath);
            return assetManager;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private Resources createResources(Context context, AssetManager assetManager) {
        Resources superRes = context.getResources();
        Resources resources = new Resources(assetManager, superRes.getDisplayMetrics(), superRes.getConfiguration());
        return resources;
    }

    public Resources getSkinResource() {
        return mResources;
    }
}

在進入Activity的時候進行檢查,如果有資源apk文件,則通過新的Resources對象進行資源獲取。

public class MainActivity extends Activity {

    private Context mContext;
    private ImageView mBgView;
    private SkinManager mSkinManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBgView = (ImageView) findViewById(R.id.bg);
        mContext = this;
        mSkinManager = new SkinManager();
        checkNewSkin();
    }

    private void checkNewSkin() {
        String skinDir = "/mnt/sdcard/skin";
        File file = new File(skinDir);
        File[] skinFile = file.listFiles();
        if (skinFile == null || skinFile.length == 0) {
            return ;
        }
        mSkinManager.loadSkinRes(mContext, skinFile[0].getAbsolutePath());
        if (mSkinManager.getSkinResource() != null) {
            mBgView.setBackgroundDrawable(mSkinManager.getSkinResource().getDrawable(R.mipmap.skin));
        }
   }
}

這里是非常簡單的處理,將編譯好的資源apk文件push到本地sd卡直接加載,正常情況下應該是從網絡下載,根據不同的模板名稱進行資源的動態替換。

 

來自:http://www.jianshu.com/p/e6125ddfaea7

 

 本文由用戶 cailongwen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!