Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中的 URI 入門:scheme、authority 與 path

編輯:Android 開發教學

就 Android 平台而言,URI 主要由三個部分構成:scheme、authority 與 path,其中 authority 又細分為 host 與 port。格式如下:

scheme://host:port/path

換成實際例子來看:

content://com.example.project:200/folder/subfolder/etc

對應關係是:scheme 為 content,host 為 com.example.project,port 為 200,path 則是 /folder/subfolder/etc,而 host 與 port 合起來就是 authority。

理解這個結構之後,data 標籤裡那些屬性的含義也就清楚了:

<data android:host="string"
android:mimeType="string"
android:path="string"
android:pathPattern="string"
android:pathPrefix="string"
android:port="string"
android:scheme="string" />

1. Uri

Uri 是通用資源標識符(Universal Resource Identifier)的縮寫,代表要操作的資料。Android 上可用的每一種資源——圖片、影片片段等——都能用 Uri 來表示。

URI 一般由三部分組成:訪問資源的命名機制、存放資源的主機名,以及資源自身的名稱(以路徑表示)。

Android 的 Uri 則由「content://」、資料的路徑、標識 ID(可選)三塊拼成。舉幾個例子:

所有聯絡人的 Uri:content://contacts/people
某個聯絡人的 Uri:content://contacts/people/5
所有圖片的 Uri:content://media/external
某張圖片的 Uri:content://media/external/images/media/4

開發時我們經常需要解析 Uri 並從中取出資料。Android 提供了兩個操作 Uri 的工具類:UriMatcher 與 ContentUris。它們雖不起眼,但熟悉之後能讓開發工作順手不少。下面就一起看看這兩個類各自扮演什麼角色。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved