編輯:Android 資訊
本文詳細梳理 Android 中原始資源檔案的組織方式與使用要點,包括各類資源的存放位置、命名限制,以及 /res/raw 與 /assets 的差異與存取方法。
和大多數平台一樣,Android 應用會用到圖片、字串等各類資源,並依類型放進對應的資料夾,例如 /res/drawable、/res/xml、/res/values、/res/raw、/res/layout 與 /assets。Android 另外鼓勵開發者用 XML 來描述 UI 版面與元件。整體而言,平台支援的資源類型有:
各資料夾的用途整理如下:
除了 /res/raw 與 /assets 之外,其餘資源在編譯時都會經過 aapt 處理:一方面把 XML 編譯成二進位形式以加快執行期讀取,另一方面則據此產生 R.java——這是程式碼存取資源時必經的入口。
/res 底下的所有檔案都會被映射進 R.java,以整數 ID 的形式標識,同類型的資源各自被封裝在一個內部類別中。生成的 R.java 大致長這樣:
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.android.explorer; public final class R { public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; } public static final class id { public static final int action=0x7f060004; public static final int description_panel=0x7f060001; public static final int fileinfo=0x7f060003; public static final int filename=0x7f060002; public static final int linearlayout_test_1=0x7f060005; public static final int linearlayout_test_2=0x7f060006; public static final int linearlayout_test_3=0x7f060007; public static final int thumbnail=0x7f060000; } public static final class layout { public static final int fileant_list_item=0x7f030000; public static final int linearlayout_test=0x7f030001; } public static final class raw { public static final int androidmanifest=0x7f040000; } public static final class string { public static final int app_name=0x7f050001; public static final int hello=0x7f050000; } }
由此可歸納出 /res 下資源定義的注意事項:
1. 同一類型(同一資料夾)下的資源不可使用相同檔名,也不能靠副檔名區分。因為 R.java 只保留檔名、忽略副檔名,若同時存在 icon.png 與 icon.jpg,R.java 中只會有一個 R.drawable.icon,另一個將無法存取。
2. 資源檔名必須符合 Java 變數命名規則,且不可含大寫字母,只能使用 [a-z0-9._]。否則會編譯失敗,因為 R.java 的變數名稱就是拿資源檔名來對應的。
3. 除了 SDK 認可的資料夾外,不可再建立子資料夾。子資料夾不會造成編譯錯誤,但會被完全忽略——例如在 /res/layout 下再建一個 activity 子資料夾,那麼 R.java 中不會出現它,裡面的內容也一併消失。
4. 資源檔案大小有上限,建議單檔不要超過 1MB,這是 SDK 文件所述的限制(有說法認為 2.2 之後放寬到 10MB,但實際情況並未經本人驗證)。
5. /res 底下的所有資源都能透過 Resources 類別搭配 ID 來存取。
使用原始資源
大多數資源在編譯時會被特殊處理,以便 APK 在執行期快速讀取。如果你希望使用未經處理的原始檔案,可以把它們放在 /res/raw 或 /assets 底下。這兩個目錄的主要差異有三點:
1. /res/raw 中的檔案會被映射到 R.java
雖然這些檔案不會被 aapt 編譯成二進位,但仍會映射進 R.java,方便以資源 ID 的形式存取。
2. 子目錄結構
/res/raw 中即使有子目錄,程式執行時也存取不到,因為 /res 底下所有非法的子目錄在 R.java 中都看不到,這些子目錄與檔案甚至不會被打包進 APK。相對地,/assets 允許子目錄、可以正常存取,並且會被打進 APK;解壓 APK 後,這些檔案依然存在,且與原始專案中的結構一致。
3. 存取方式
/res/raw 底下的檔案只能透過 Resources 並提供資源 ID 來存取:
InputStream in = Context.getResources().openRawResource(R.id.filename);
這也解釋了子資料夾為何無法存取——因為根本沒有對應的 ID。而 /assets 則需透過 AssetManager 存取,以下重點說明。
透過 AssetManager 存取 /assets
1. 檔案讀取
使用 AssetManager.open(String filename) 開啟檔案,這是一組重載方法,另有參數可設定開啟模式,細節可查閱官方文件。此處的 filename 是相對於 /assets 的路徑:
InputStream in = mAssetManager.open("hello.txt"); // '/assets/hello.txt' InputStream in2 = mAssetManager.open("config/ui.txt"); // '/assets/config/ui.txt'
2. 資料夾處理——如何遍歷 /assets
若想存取 /assets 下的檔案,必須知道檔名與相對路徑。若事前不確定內容,就得先列出該路徑下的所有檔案再挑選。AssetManager 提供了 list() 方法:
public final String[] list(String path) Since: API Level 1 Return a String array of all the assets at the given path. Parameters path A relative path within the assets, i.e., "docs/home.html". Returns String[] Array of strings, one for each asset. These file names are relative to 'path'. You can open the file by concatenating 'path' and a name in the returned string (via File) and passing that to open().
這段文件其實寫得含糊,list() 列出的是某個資料夾下的檔案,因此傳入的應該是資料夾路徑,而非文件範例中的 "docs/home.html"。更麻煩的問題是如何列出根目錄 /assets 的內容,因為不知道根層級有什麼,就無從往子目錄深入。文件對參數該怎麼傳並未講清楚,實測的結果是:
mAssetManager.list("."); // returns array size is 0 mAssetManager.list("/"); // returns [AndroidManifest.xml, META-INF, assets, classes.dex, res, resources.arsc] // don't worry, u can see these files though, no way to access them mAssetManager.list("/assets"); // returns array size is 0 mAssetManager.list(""); // returns stuff in /assets
也就是傳入空字串才是正解。取得子項後再遞迴往下遍歷,直到把所有檔案找出來為止。
常見問題
1. 資源檔案只能以 InputStream 取得
若需要檔案 URI 或想直接操作檔案,光靠 API 是不夠的,它只給你一個唯讀的串流。可行的做法是先把內容讀出來寫進暫存檔,再對暫存檔進行後續操作,暫存檔可透過 Context 提供的介面建在內部或外部儲存空間:
File File.createTempFile(String prefix, String suffix); File File.createTempFile(String prefix, String suffix, File path);
要注意系統特性帶來的權限問題。例如第一個方法使用的是 "java.io.tmpdir",在 Android 上等同 "/sdcard",因此當裝置沒有 SD 卡時必然拋出例外。
2. 所有資源檔案都是唯讀,執行期無法修改
因為程式執行時是把 APK 動態解析載入記憶體,APK 本身不會改變。
3. /res 與 /assets 兩個資源資料夾同樣唯讀,無法寫入,原因同上:APK 一旦編譯完成就不再變動。
以下範例可遞迴遍歷 /assets 下所有資料夾與檔案:
package com.android.explorer; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.content.res.AssetManager; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.MimeTypeMap; import android.widget.BaseAdapter; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; /* * Explore all stuff in /assets and perform actions specified by users. */ public class FileAntActivity extends ListActivity { private static final String TAG = "FileAntActivity"; private AssetManager mAssetManager; private static final String EXTRA_CURRENT_DIRECTORY = "current_directory"; private static final String EXTRA_PARENT = "parent_directory"; public static final String FILEANT_VIEW = "com.android.fileant.VIEW"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); String current = null; String parent = null; if (intent != null && intent.hasExtra(EXTRA_CURRENT_DIRECTORY)) { current = intent.getStringExtra(EXTRA_CURRENT_DIRECTORY); } if (current == null) { current = ""; } if (intent != null && intent.hasExtra(EXTRA_PARENT)) { parent = intent.getStringExtra(EXTRA_PARENT); } if (parent == null) { parent = ""; } mAssetManager = getAssets(); if (TextUtils.isEmpty(parent)) { setTitle("/assets"); } else { setTitle(parent); } try { // List all the stuff in /assets if (!TextUtils.isEmpty(parent)) { current = parent + File.separator + current; } Log.e(TAG, "current: '" + current + "'"); String[] stuff = mAssetManager.list(current); setListAdapter(new FileAntAdapter(this, stuff, current)); } catch (IOException e) { e.printStackTrace(); } } private class FileAntAdapter extends BaseAdapter { private Context mContext; private String[] mEntries; private String mParentDirectory; public FileAntAdapter(Context context, String[] data, String parent) { mContext = context; this.mEntries = data; mParentDirectory = parent; } public int getCount() { return mEntries.length; } public Object getItem(int position) { return mEntries[position]; } public long getItemId(int position) { return (long) position; } public View getView(final int position, View item, ViewGroup parent) { LayoutInflater factory = LayoutInflater.from(mContext); if (item == null) { item = factory.inflate(R.layout.fileant_list_item, null); TextView filename = (TextView) item.findViewById(R.id.filename); TextView fileinfo = (TextView) item.findViewById(R.id.fileinfo); ImageButton action = (ImageButton) item.findViewById(R.id.action); final String entry = mEntries[position]; filename.setText(entry); boolean isDir = isDirectory(entry); if (isDir) { fileinfo.setText("Click to view folder"); action.setVisibility(View.GONE); item.setClickable(true); item.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent intent = new Intent(FILEANT_VIEW); intent.putExtra(EXTRA_CURRENT_DIRECTORY, entry); intent.putExtra(EXTRA_PARENT, mParentDirectory); startActivity(intent); } }); } else { final String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(getExtension(entry)); fileinfo.setText(type); item.setClickable(false); action.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String filepath = entry; if (!TextUtils.isEmpty(mParentDirectory)) { filepath = mParentDirectory + File.separator + filepath; } BufferedInputStream in = new BufferedInputStream(mManager.open(filepath)); // Do whatever you like with this input stream } }); } } return item; } } /** * Test Whether an entry is a file or directory based on the rule: * File: has extension *.*, or starts with ".", which is a hidden files in Unix/Linux, * otherwise, it is a directory * @param filename * @return */ private boolean isDirectory(String filename) { return !(filename.startsWith(".") || (filename.lastIndexOf(".") != -1)); } private String getExtension(String filename) { int index = filename.lastIndexOf("."); if (index == -1) { return ""; } return filename.substring(index + 1, filename.length()).toLowerCase(); } }
總結來說,/res 下的資源結構嚴格、以 ID 存取,適合放 UI 相關的靜態內容;/assets 則保留原始目錄結構、以路徑存取,適合放設定檔、資料檔等需要自行解析的內容。選對存放位置,能省下不少後續處理的功夫。
invisible 和 gone 差在哪?Android 可見性屬性完整對比
Android 裡幾乎每個 View 都有 visibility 屬性,取值只有三個:visible、invisible、gone。看起來都是「顯示 / 不顯示」,但 i
用 MVP 架構重整 Android 應用層
在傳統 Android 開發中,Activity 常同時負責畫面、邏輯與資料處理,導致職責過重,也讓測試變得困難。MVP 架構把 View、Model 與 Present
正確使用 Android 性能分析工具 TraceView
前面唠叨 最近公司 app 中有些列表在滑動時會有卡頓現象,我便著手解決這些問題。解決問題之前,首先要分析列表滑動的性能瓶頸在哪裡。因為之前不會正確使用 TraceVie
Android 記憶體優化:LruCache 圖片快取解析
什麼是快取 快取的核心概念,是把常用資料暫時放在一個更容易存取的區域,避免每次都從原始來源重新讀取。對 Android 應用來說,圖片、網路回應、設定資料等,都適合透過快