> 編寫:[jdneo](https://github.com/jdneo) - 原文:[http://developer.android.com/training/secure-file-sharing/sharing-file.html](http://developer.android.com/training/secure-file-sharing/sharing-file.html)
在上一節課中,我們對應用程序進行了配置,使得它可以使用Content URI來共享文件了,現在你可以響應其他應用程序的文件請求。一種響應這些請求的方法是在服務端應用程序提供一個文件選擇接口,它可以由其他應用激活。這種方法可以允許客戶端應用程序讓用戶從服務端應用程序選擇一個文件,然后接收這個文件的Content URI。
這節課將會向你展示如何在你的應用中創建一個用來選擇文件的[Activity](# "An activity represents a single screen with a user interface."),來響應這些索取文件的請求。
### 接收文件請求
為了從客戶端應用程序接收一個文件索取請求,然后以Content URI的形式進行響應,你的應用程序應該提供一個選擇文件的[Activity](# "An activity represents a single screen with a user interface.")。客戶端應用程序通過調用[startActivityForResult()](http://developer.android.com/reference/android/app/Activity.html#startActivityForResult(android.content.Intent, int))來啟動這個[Activity](# "An activity represents a single screen with a user interface.")。該方法包含了一個[Intent](http://developer.android.com/reference/android/content/Intent.html)參數,它具有[ACTION_PICK](http://developer.android.com/reference/android/content/Intent.html#ACTION_PICK)這一Action。當客戶端應用程序調用了[startActivityForResult()](http://developer.android.com/reference/android/app/Activity.html#startActivityForResult(android.content.Intent, int)),你的應用可以向客戶端應用程序返回一個結果,該結果即用戶所選擇的文件所對應的Content URI。
學習如何在客戶端應用程序實現文件索取請求,可以閱讀:[請求分享一個文件](#)。
### 創建一個選擇文件的[Activity](# "An activity represents a single screen with a user interface.")
為了配置一個選擇文件的[Activity](# "An activity represents a single screen with a user interface."),我們首先需要在Manifest清單文件中定義你的[Activity](# "An activity represents a single screen with a user interface."),在其Intent過濾器中,匹配[ACTION_PICK](http://developer.android.com/reference/android/content/Intent.html#ACTION_PICK)這一Action,以及[CATEGORY_DEFAULT](http://developer.android.com/reference/android/content/Intent.html#CATEGORY_DEFAULT)和[CATEGORY_OPENABLE](http://developer.android.com/reference/android/content/Intent.html#CATEGORY_OPENABLE)這兩種Category。另外,還需要為你的應用程序設置MIME類型過濾器,來表明你的應用程序可以向其他應用程序提供哪種類型的文件。下面的這段代碼展示了如何在清單文件中定義新的[Activity](# "An activity represents a single screen with a user interface.")和Intent過濾器:
~~~
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
...
<application>
...
<activity
android:name=".FileSelectActivity"
android:label="File Selector" >
<intent-filter>
<action
android:name="android.intent.action.PICK"/>
<category
android:name="android.intent.category.DEFAULT"/>
<category
android:name="android.intent.category.OPENABLE"/>
<data android:mimeType="text/plain"/>
<data android:mimeType="image/*"/>
</intent-filter>
</activity>
~~~
### 在代碼中定義文件選擇[Activity](# "An activity represents a single screen with a user interface.")
下面,定義一個[Activity](# "An activity represents a single screen with a user interface.")子類,它用來顯示在你內部存儲的“files/images/”目錄下可以獲得的文件,然后允許用戶選擇期望的文件。下面的代碼展示了如何定義這個[Activity](# "An activity represents a single screen with a user interface."),并令其響應用戶的選擇:
~~~
public class MainActivity extends Activity {
// The path to the root of this app's internal storage
private File mPrivateRootDir;
// The path to the "images" subdirectory
private File mImagesDir;
// Array of files in the images subdirectory
File[] mImageFiles;
// Array of filenames corresponding to mImageFiles
String[] mImageFilenames;
// Initialize the Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
...
// Set up an Intent to send back to apps that request a file
mResultIntent =
new Intent("com.example.myapp.ACTION_RETURN_FILE");
// Get the files/ subdirectory of internal storage
mPrivateRootDir = getFilesDir();
// Get the files/images subdirectory;
mImagesDir = new File(mPrivateRootDir, "images");
// Get the files in the images subdirectory
mImageFiles = mImagesDir.listFiles();
// Set the Activity's result to null to begin with
setResult(Activity.RESULT_CANCELED, null);
/*
* Display the file names in the ListView mFileListView.
* Back the ListView with the array mImageFilenames, which
* you can create by iterating through mImageFiles and
* calling File.getAbsolutePath() for each File
*/
...
}
...
}
~~~
### 響應一個文件選擇
一旦用戶選擇了一個想要共享的文件,你的應用程序必須明確哪個文件被選擇了,然后為這個文件生成一個對應的Content URI。如果我們的[Activity](# "An activity represents a single screen with a user interface.")在[ListView](http://developer.android.com/reference/android/widget/ListView.html)中顯示了可獲得文件的清單,那么當用戶點擊了一個文件名時,系統會調用方法[onItemClick()](http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html#onItemClick(android.widget.AdapterView<?>, android.view.View, int, long)),在該方法中你可以獲取被選擇的文件。
在[onItemClick()](http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html#onItemClick(android.widget.AdapterView<?>, android.view.View, int, long))中,根據被選中文件的文件名獲取一個[File](http://developer.android.com/reference/java/io/File.html)對象,然后將它作為參數傳遞給[getUriForFile()](http://developer.android.com/reference/android/support/v4/content/FileProvider.html#getUriForFile(android.content.Context, java.lang.String, java.io.File)),另外還需傳入的參數是你在[`<provider>`](http://developer.android.com/guide/topics/manifest/provider-element.html)標簽中為[FileProvider](http://developer.android.com/reference/android/support/v4/content/FileProvider.html)所指定的Authority,函數返回的Content URI包含了相應的Authority,一個對應于文件目錄的路徑標記(如在XML meta-data中定義的),以及包含擴展名的文件名。有關[FileProvider](http://developer.android.com/reference/android/support/v4/content/FileProvider.html)如何基于XML meta-data將目錄路徑與路徑標記進行匹配的知識,可以閱讀:[指定可共享目錄路徑](#)。
下面的例子展示了如何檢測選中的文件并且獲得它的Content URI:
~~~
protected void onCreate(Bundle savedInstanceState) {
...
// Define a listener that responds to clicks on a file in the ListView
mFileListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
/*
* When a filename in the ListView is clicked, get its
* content URI and send it to the requesting app
*/
public void onItemClick(AdapterView<?> adapterView,
View view,
int position,
long rowId) {
/*
* Get a File for the selected file name.
* Assume that the file names are in the
* mImageFilename array.
*/
File requestFile = new File(mImageFilename[position]);
/*
* Most file-related method calls need to be in
* try-catch blocks.
*/
// Use the FileProvider to get a content URI
try {
fileUri = FileProvider.getUriForFile(
MainActivity.this,
"com.example.myapp.fileprovider",
requestFile);
} catch (IllegalArgumentException e) {
Log.e("File Selector",
"The selected file can't be shared: " +
clickedFilename);
}
...
}
});
...
}
~~~
記住,你能生成的那些Content URI所對應的文件,是那些在meta-data文件中包含`<paths>`標簽的(即你定義的)目錄內的文件,這方面知識在[Specify Sharable Directories](http://developer.android.com/training/secure-file-sharing/setup-sharing.html#DefineMetaData)中已經討論過。如果你調用[getUriForFile()](http://developer.android.com/reference/android/support/v4/content/FileProvider.html#getUriForFile(android.content.Context, java.lang.String, java.io.File))方法所要獲取的文件不在你指定的目錄中,你會收到一個[IllegalArgumentException](http://developer.android.com/reference/java/lang/IllegalArgumentException.html)。
### 為文件授權
現在已經有了你想要共享給其他應用程序的文件所對應的Content URI,你需要允許客戶端應用程序訪問這個文件。為了達到這一目的,可以通過將Content URI添加至一個[Intent](http://developer.android.com/reference/android/content/Intent.html)中,然后為該[Intent](http://developer.android.com/reference/android/content/Intent.html)設置權限標記。你所授予的權限是臨時的,并且當接收文件的應用程序的任務棧終止后,會自動過期。
下面的例子展示了如何為文件設置讀權限:
~~~
protected void onCreate(Bundle savedInstanceState) {
...
// Define a listener that responds to clicks in the ListView
mFileListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView,
View view,
int position,
long rowId) {
...
if (fileUri != null) {
// Grant temporary read permission to the content URI
mResultIntent.addFlags(
Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
...
}
...
});
...
}
~~~
> **Caution:**只有調用[setFlags()](http://developer.android.com/reference/android/content/Intent.html#setFlags(int))來為你的文件授予臨時被訪問權限才是唯一的,安全的方法。盡量避免對文件的Content URI調用[Context.grantUriPermission()](http://developer.android.com/reference/android/content/Context.html#grantUriPermission(java.lang.String, android.net.Uri, int)),因為通過該方法授予的權限,你只能通過調用[Context.revokeUriPermission()](http://developer.android.com/reference/android/content/Context.html#revokeUriPermission(android.net.Uri, int))來撤銷。
### 與請求應用共享文件
為了向請求文件的應用程序提供其需要的文件,我們將包含了Content URI和相應權限的[Intent](http://developer.android.com/reference/android/content/Intent.html)傳遞給[setResult()](http://developer.android.com/reference/android/app/Activity.html#setResult(int))。當你定義的[Activity](# "An activity represents a single screen with a user interface.")結束后,系統會把這個包含了Content URI的[Intent](http://developer.android.com/reference/android/content/Intent.html)傳遞給客戶端應用程序。下面的例子展示了其中的核心步驟:
~~~
protected void onCreate(Bundle savedInstanceState) {
...
// Define a listener that responds to clicks on a file in the ListView
mFileListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView,
View view,
int position,
long rowId) {
...
if (fileUri != null) {
...
// Put the Uri and MIME type in the result Intent
mResultIntent.setDataAndType(
fileUri,
getContentResolver().getType(fileUri));
// Set the result
MainActivity.this.setResult(Activity.RESULT_OK,
mResultIntent);
} else {
mResultIntent.setDataAndType(null, "");
MainActivity.this.setResult(RESULT_CANCELED,
mResultIntent);
}
}
});
~~~
當用戶選擇好文件后,我們應該向用戶提供一個能夠立即回到客戶端應用程序的方法。一種實現的方法是向用戶提供一個勾選框或者一個完成按鈕。可以使用按鈕的[android:onClick](http://developer.android.com/reference/android/view/View.html#attr_android:onClick)屬性字段為它關聯一個方法。在該方法中,調用[finish()](http://developer.android.com/reference/android/app/Activity.html#finish())。例如:
~~~
public void onDoneClick(View v) {
// Associate a method with the Done button
finish();
}
~~~
- 序言
- Android入門基礎:從這里開始
- 建立第一個App
- 創建Android項目
- 執行Android程序
- 建立簡單的用戶界面
- 啟動其他的Activity
- 添加ActionBar
- 建立ActionBar
- 添加Action按鈕
- 自定義ActionBar的風格
- ActionBar的覆蓋層疊
- 兼容不同的設備
- 適配不同的語言
- 適配不同的屏幕
- 適配不同的系統版本
- 管理Activity的生命周期
- 啟動與銷毀Activity
- 暫停與恢復Activity
- 停止與重啟Activity
- 重新創建Activity
- 使用Fragment建立動態的UI
- 創建一個Fragment
- 建立靈活動態的UI
- Fragments之間的交互
- 數據保存
- 保存到Preference
- 保存到文件
- 保存到數據庫
- 與其他應用的交互
- Intent的發送
- 接收Activity返回的結果
- Intent過濾
- Android分享操作
- 分享簡單的數據
- 給其他App發送簡單的數據
- 接收從其他App返回的數據
- 給ActionBar增加分享功能
- 分享文件
- 建立文件分享
- 分享文件
- 請求分享一個文件
- 獲取文件信息
- 使用NFC分享文件
- 發送文件給其他設備
- 接收其他設備的文件
- Android多媒體
- 管理音頻播放
- 控制音量與音頻播放
- 管理音頻焦點
- 兼容音頻輸出設備
- 拍照
- 簡單的拍照
- 簡單的錄像
- 控制相機硬件
- 打印
- 打印照片
- 打印HTML文檔
- 打印自定義文檔
- Android圖像與動畫
- 高效顯示Bitmap
- 高效加載大圖
- 非UI線程處理Bitmap
- 緩存Bitmap
- 管理Bitmap的內存
- 在UI上顯示Bitmap
- 使用OpenGL ES顯示圖像
- 建立OpenGL ES的環境
- 定義Shapes
- 繪制Shapes
- 運用投影與相機視圖
- 添加移動
- 響應觸摸事件
- 添加動畫
- View間漸變
- 使用ViewPager實現屏幕側滑
- 展示卡片翻轉動畫
- 縮放View
- 布局變更動畫
- Android網絡連接與云服務
- 無線連接設備
- 使得網絡服務可發現
- 使用WiFi建立P2P連接
- 使用WiFi P2P服務
- 執行網絡操作
- 連接到網絡
- 管理網絡
- 解析XML數據
- 高效下載
- 為網絡訪問更加高效而優化下載
- 最小化更新操作的影響
- 避免下載多余的數據
- 根據網絡類型改變下載模式
- 云同步
- 使用備份API
- 使用Google Cloud Messaging
- 解決云同步的保存沖突
- 使用Sync Adapter傳輸數據
- 創建Stub授權器
- 創建Stub Content Provider
- 創建Sync Adpater
- 執行Sync Adpater
- 使用Volley執行網絡數據傳輸
- 發送簡單的網絡請求
- 建立請求隊列
- 創建標準的網絡請求
- 實現自定義的網絡請求
- Android聯系人與位置信息
- Android聯系人信息
- 獲取聯系人列表
- 獲取聯系人詳情
- 使用Intents修改聯系人信息
- 顯示聯系人頭像
- Android位置信息
- 獲取最后可知位置
- 獲取位置更新
- 顯示位置地址
- 創建和監視地理圍欄
- Android可穿戴應用
- 賦予Notification可穿戴特性
- 創建Notification
- 在Notifcation中接收語音輸入
- 為Notification添加顯示頁面
- 以Stack的方式顯示Notifications
- 創建可穿戴的應用
- 創建并運行可穿戴應用
- 創建自定義的布局
- 添加語音功能
- 打包可穿戴應用
- 通過藍牙進行調試
- 創建自定義的UI
- 定義Layouts
- 創建Cards
- 創建Lists
- 創建2D-Picker
- 創建確認界面
- 退出全屏的Activity
- 發送并同步數據
- 訪問可穿戴數據層
- 同步數據單元
- 傳輸資源
- 發送與接收消息
- 處理數據層的事件
- Android TV應用
- 創建TV應用
- 創建TV應用的第一步
- 處理TV硬件部分
- 創建TV的布局文件
- 創建TV的導航欄
- 創建TV播放應用
- 創建目錄瀏覽器
- 提供一個Card視圖
- 創建詳情頁
- 顯示正在播放卡片
- 幫助用戶在TV上探索內容
- TV上的推薦內容
- 使得TV App能夠被搜索
- 使用TV應用進行搜索
- 創建TV游戲應用
- 創建TV直播應用
- TV Apps Checklist
- Android企業級應用
- Ensuring Compatibility with Managed Profiles
- Implementing App Restrictions
- Building a Work Policy Controller
- Android交互設計
- 設計高效的導航
- 規劃屏幕界面與他們之間的關系
- 為多種大小的屏幕進行規劃
- 提供向下和橫向導航
- 提供向上和歷史導航
- 綜合:設計樣例 App
- 實現高效的導航
- 使用Tabs創建Swipe視圖
- 創建抽屜導航
- 提供向上的導航
- 提供向后的導航
- 實現向下的導航
- 通知提示用戶
- 建立Notification
- 當啟動Activity時保留導航
- 更新Notification
- 使用BigView風格
- 顯示Notification進度
- 增加搜索功能
- 建立搜索界面
- 保存并搜索數據
- 保持向下兼容
- 使得你的App內容可被Google搜索
- 為App內容開啟深度鏈接
- 為索引指定App內容
- Android界面設計
- 為多屏幕設計
- 兼容不同的屏幕大小
- 兼容不同的屏幕密度
- 實現可適應的UI
- 創建自定義View
- 創建自定義的View類
- 實現自定義View的繪制
- 使得View可交互
- 優化自定義View
- 創建向后兼容的UI
- 抽象新的APIs
- 代理至新的APIs
- 使用舊的APIs實現新API的效果
- 使用版本敏感的組件
- 實現輔助功能
- 開發輔助程序
- 開發輔助服務
- 管理系統UI
- 淡化系統Bar
- 隱藏系統Bar
- 隱藏導航Bar
- 全屏沉浸式應用
- 響應UI可見性的變化
- 創建使用Material Design的應用
- 開始使用Material Design
- 使用Material的主題
- 創建Lists與Cards
- 定義Shadows與Clipping視圖
- 使用Drawables
- 自定義動畫
- 維護兼容性
- Android用戶輸入
- 使用觸摸手勢
- 檢測常用的手勢
- 跟蹤手勢移動
- Scroll手勢動畫
- 處理多觸摸手勢
- 拖拽與縮放
- 管理ViewGroup中的觸摸事件
- 處理鍵盤輸入
- 指定輸入法類型
- 處理輸入法可見性
- 兼容鍵盤導航
- 處理按鍵動作
- 兼容游戲控制器
- 處理控制器輸入動作
- 支持不同的Android系統版本
- 支持多個控制器
- Android后臺任務
- 在IntentService中執行后臺任務
- 創建IntentService
- 發送工作任務到IntentService
- 報告后臺任務執行狀態
- 使用CursorLoader在后臺加載數據
- 使用CursorLoader執行查詢任務
- 處理查詢的結果
- 管理設備的喚醒狀態
- 保持設備的喚醒
- 制定重復定時的任務
- Android性能優化
- 管理應用的內存
- 代碼性能優化建議
- 提升Layout的性能
- 優化layout的層級
- 使用include標簽重用layouts
- 按需加載視圖
- 使得ListView滑動順暢
- 優化電池壽命
- 監測電量與充電狀態
- 判斷與監測Docking狀態
- 判斷與監測網絡連接狀態
- 根據需要操作Broadcast接受者
- 多線程操作
- 在一個線程中執行一段特定的代碼
- 為多線程創建線程池
- 啟動與停止線程池中的線程
- 與UI線程通信
- 避免出現程序無響應ANR
- JNI使用指南
- 優化多核處理器(SMP)下的Android程序
- Android安全與隱私
- Security Tips
- 使用HTTPS與SSL
- 為防止SSL漏洞而更新Security
- 使用設備管理條例增強安全性
- Android測試程序
- 測試你的Activity
- 建立測試環境
- 創建與執行測試用例
- 測試UI組件
- 創建單元測試
- 創建功能測試
- 術語表