讀取 其他Apk 中的資源檔案

2021-07-10 03:30:13 字數 1781 閱讀 2234

如果是在做一些 主題 **之類的功能.

很多都是把 相應主題的資源 放到 乙個apk.

其實還有一種 放開 可以 不用 安裝這個apk 而且就能 載入這個apk 的資源,

而且 還能執行一些相應的方法...

如果是 安裝了這個主題 apk 然後再載入 相應的資源 可以使用如下方法.

int id = resources.getidentifier(name, "drawable", pkg);

通過傳入  name , pkg 包名 就能得到 相應包名下 對應名字的資源檔案.

然後就可以直接用了 

但是如果不安裝 apk 該怎麼使用呢?

由於 apk 沒有安裝我們就能很好的通過 res 直接過去相應的資源檔案.

那麼我們就需要 把這個apk 中的資源檔案載入出來 … 

在網上看到了如下方法: 

//這個方法把我們主題apk裡的resource 加入到我們自己的主apk裡的resource裡

//這個dexpath就是 我們theme.apk在 我們主apk 的存放路徑

private void addotherresourcestomain(string dexpath) catch (instantiationexception e) catch (illegalacces***ception e) catch (nosuchmethodexception e) catch (invocationtargetexception e)

//把themeapk裡的資源 通過addassetpath 這個方法增加到本apk自己的path裡面以後 就可以重新構建出resource物件了

mresource = new resources(massetmanager, getresources().getdisplaymetrics(), getresources().getconfiguration());

}

然後就可以通過  

int id = resources.getidentifier(name, "drawable", pkg);

獲取相應的資源檔案...

下面在說說  執行 其他 apk 中的一些方法問題 

//是dex的輸出路徑(因為載入apk/jar的時候會解壓出dex檔案,這個路徑就是儲存dex檔案的)

string optimizeddirectory = getcachedir() + file.separator;

//這個也是pathclassloader作為預設的類載入器的原因,因為一般程式都是安裝了,

classloader classloader = new dexclassloader(themeapkpath, optimizeddirectory, null, getclassloader());

//把 theme apk 中的res 載入進來

addotherresourcestomain(themeapkpath);

try catch (exception e)

其實就是 new 出乙個 dexclassloader 然後通過這個 class loader 去反射執行方法 

當然執行的方法不能 和 context 這些 生命週期 有關的方法, 不然會出錯.

不過有一點需要注意的是  

new dexclassloader(themeapkpath, optimizeddirectory, null, getclassloader()); 方法中 

看一下 我上面執行的方法的原始碼吧: 

讀取資源檔案

資源檔案在存放彈出資訊很有用,以下是讀資源檔案的簡單 dim rm as resourcemanager new resourcemanager readresx.message system.reflection.assembly.getexecutingassembly dim ci as cu...

c 讀取資源檔案

全域性資源檔案 getglobalresourceobject string param1,string param2 讀取全域性資源檔案的方法 引數說明 param1 資源檔案類名 即資源檔名,不帶resx param2 鍵值名 區域性資源檔案 getlocalresourceobject str...

讀取properties資源檔案

方法一 在servlet中利用servletcontext物件讀取配置檔案 this.getservletcontext getresource web inf classes db.properties inputstream in url.openstream properties prop n...