使用 Android 資產

資產 可讓您在應用程式中包含任意檔案,例如文字、xml、字型、音樂和視訊。 如果您嘗試將這些檔案包含為「資源」,Android 會將這些檔案處理到其資源系統中,而且您將無法取得原始數據。 如果您想要存取未變更的數據,Assets 是其中一種方式。

新增至專案的資產會顯示為文件系統,而文件系統可以使用 AssetManager 從中讀取。 在這個簡單的示範中,我們將將文本文件資產新增至專案、使用 AssetManager讀取它,並將其顯示在 TextView 中。

將資產新增至專案

資產會移至 Assets 您項目的資料夾中。 將新的文字檔新增至名為 read_asset.txt的這個資料夾。 將一些文字放在它,就像「我來自資產!

Visual Studio 應該已將此檔案的 建置動作 設定為 AndroidAsset

Setting the build action to AndroidAsset

選取正確的 BuildAction 可確保檔案會在編譯時期封裝到 APK 中。

讀取資產

資產是使用 AssetManager 讀取的。 藉由存取 上的 Android.Content.ContextAssets 屬性,例如 Activity,即可取得 AssetManager實例。 在下列程式代碼中,我們會開啟 read_asset.txt 資產、讀取內容,並使用 TextView 加以顯示。

protected override void OnCreate (Bundle bundle)
{
    base.OnCreate (bundle);

    // Create a new TextView and set it as our view
    TextView tv = new TextView (this);
    
    // Read the contents of our asset
    string content;
    AssetManager assets = this.Assets;
    using (StreamReader sr = new StreamReader (assets.Open ("read_asset.txt")))
    {
        content = sr.ReadToEnd ();
    }

    // Set TextView.Text to our asset content
    tv.Text = content;
    SetContentView (tv);
}

讀取二進位資產

上述範例中的 用法 StreamReader 非常適合用於文字資產。 針對二進位資產,請使用下列程序代碼:

protected override void OnCreate (Bundle bundle)
{
    base.OnCreate (bundle);

    // Read the contents of our asset
    const int maxReadSize = 256 * 1024;
    byte[] content;
    AssetManager assets = this.Assets;
    using (BinaryReader br = new BinaryReader (assets.Open ("mydatabase.db")))
    {
        content = br.ReadBytes (maxReadSize);
    }

    // Do something with it...

}

執行應用程式

執行應用程式,您應該會看到下列內容:

Example screenshot