首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android res/xml 目錄下的 XML 文件運行時不可修改:只讀資源機制與替代方案

     編輯:程式設計綜合問答

問題背景

嘗試在運行時修改 res/xml/ 下的 XML 文件屬性(如 android:requiredDeviceUnlock),發現 getResources().getXml() 返回 XmlResourceParser 僅支持解析,不支持寫入。

根本原因

res/ 目錄下的所有資源在打包時被編譯進 APK,屬於只讀資產。Android 安全模型禁止應用在運行時修改自身安裝包內的文件。

替代方案

方案適用場景實現要點
SharedPreferences鍵值對配置、啟用/禁用標志getSharedPreferences("config", MODE_PRIVATE).edit().putBoolean("require_unlock", true).apply()
內部存儲文件結構化配置、需保持 XML 格式context.getFilesDir() 讀寫私有文件,首次從 assets 複製模板
DataStore (Jetpack)現代異步配置存儲、類型安全PreferencesDataStore 或 ProtoDataStore 替代 SharedPreferences
遠程配置動態下發、A/B 測試Firebase Remote Config 或自建配置中心

代碼示例:內部存儲 XML 讀寫

File xmlFile = new File(context.getFilesDir(), "device_config.xml");
if (!xmlFile.exists()) {
    // 首次從 assets 複製默認配置
    try (InputStream in = context.getAssets().open("device_config.xml");
         FileOutputStream out = new FileOutputStream(xmlFile)) {
        byte[] buf = new byte[1024]; int len;
        while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
    }
}
// 修改
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = factory.newDocumentBuilder().parse(xmlFile);
Element root = doc.getDocumentElement();
root.setAttribute("requiredDeviceUnlock", "true");
// 保存
TransformerFactory.newInstance().newTransformer()
    .transform(new DOMSource(doc), new StreamResult(xmlFile));

總結

拋棄修改 res/xml 的想法,改用應用沙箱內的可寫存儲方案,符合 Android 安全模型且靈活可控。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved