私有void showFileChooser() {
意向意向=新意向(意向。ACTION _ GET _ CONTENT);
intent . settype(" */* ");
intent.addCategory(Intent。類別_可打開);
嘗試{
startActivityForResult(intent . create chooser(intent,“選擇要上傳的文件”),File _ Select _ CODE);
} catch(Android . content . activitynotfoundexception ex){
Toast.makeText(這個,“請安裝壹個文件管理器。”,吐司。LENGTH_SHORT)。show();
}
}
選擇結果:
@覆蓋
受保護的void on activity result(int request code,int resultCode,Intent data) {
開關(請求代碼){
案例文件_選擇_代碼:
if (resultCode == RESULT_OK) {
//獲取選定文件的Uri
uri uri = data . get data();
string path = file utils . getpath(this,uri);
}
打破;
}
super . on activity result(request code,resultCode,data);
}
FileUtils文件
公共類FileUtils {
公共靜態字符串getPath(上下文Context,Uri uri) {
if(“內容”。equalsIgnoreCase(uri . get scheme())){
string[]projection = { " _ data " };
Cursor cursor = null
嘗試{
cursor = context . getcontentresolver()。query(uri,projection,null,null,null);
int column _ index = cursor . getcolumnindexorthrow(" _ data ");
if (cursor.moveToFirst()) {
返回cursor . getstring(column _ index);
}
} catch(異常e) {
//吃了它
}
}
else if ("file "。equalsIgnoreCase(uri . get scheme())){
返回uri . getpath();
}
返回null
}
}