下面列出了怎么用android.provider.DocumentsContract的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void createFolder(String new_name)
{
try
{
Uri new_uri = DocumentsContract.createDocument(ctx.getContentResolver(), uri, Document.MIME_TYPE_DIR,
new_name);
if (new_uri != null)
{
notifyRefr(new_name);
return;
}
}
catch (Exception e)
{
e.printStackTrace();
}
notify(ctx.getString(R.string.fman_create_folder_error, new_name), CommanderIf.OPERATION_FAILED);
}
public static Uri[] listFiles(Context context, Uri self) {
final ContentResolver resolver = context.getContentResolver();
final Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(self,
DocumentsContract.getDocumentId(self));
final ArrayList<Uri> results = new ArrayList<Uri>();
Cursor c = null;
try {
c = resolver.query(childrenUri, new String[] {
DocumentsContract.Document.COLUMN_DOCUMENT_ID }, null, null, null);
while (c.moveToNext()) {
final String documentId = c.getString(0);
final Uri documentUri = DocumentsContract.buildDocumentUriUsingTree(self,
documentId);
results.add(documentUri);
}
} catch (Exception e) {
Log.w(TAG, "Failed query: " + e);
} finally {
closeQuietly(c);
}
return results.toArray(new Uri[results.size()]);
}
public @Nullable Intent buildBrowseIntentForUser(int userId) {
final Uri uri;
if (type == VolumeInfo.TYPE_PUBLIC && mountUserId == userId) {
uri = DocumentsContract.buildRootUri(DOCUMENT_AUTHORITY, fsUuid);
} else if (type == VolumeInfo.TYPE_EMULATED && isPrimary()) {
uri = DocumentsContract.buildRootUri(DOCUMENT_AUTHORITY,
DOCUMENT_ROOT_PRIMARY_EMULATED);
} else {
return null;
}
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setDataAndType(uri, DocumentsContract.Root.MIME_TYPE_ITEM);
// note that docsui treats this as *force* show advanced. So sending
// false permits advanced to be shown based on user preferences.
intent.putExtra(DocumentsContract.EXTRA_SHOW_ADVANCED, isPrimary());
return intent;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.sample_action) {
toggleLogin();
item.setTitle(mLoggedIn ? R.string.log_out : R.string.log_in);
// BEGIN_INCLUDE(notify_change)
// Notify the system that the status of our roots has changed. This will trigger
// a call to MyCloudProvider.queryRoots() and force a refresh of the system
// picker UI. It's important to call this or stale results may persist.
getActivity().getContentResolver().notifyChange(DocumentsContract.buildRootsUri
(AUTHORITY), null, false);
// END_INCLUDE(notify_change)
}
return true;
}
private static boolean isDocumentsProviderCached(Context context, String authority) {
if (providersCache.containsKey(authority)) {
Boolean b = providersCache.get(authority);
if (b != null) return b;
}
final Intent intent = new Intent(DocumentsContract.PROVIDER_INTERFACE);
final List<ResolveInfo> infos = context.getPackageManager()
.queryIntentContentProviders(intent, 0);
for (ResolveInfo info : infos) {
if (authority.equals(info.providerInfo.authority)) {
providersCache.put(authority, true);
return true;
}
}
providersCache.put(authority, false);
return false;
}
public static Uri[] listFiles(Context context, Uri self) {
final ContentResolver resolver = context.getContentResolver();
final Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(self,
DocumentsContract.getDocumentId(self));
final ArrayList<Uri> results = new ArrayList<Uri>();
Cursor c = null;
try {
c = resolver.query(childrenUri, new String[] {
DocumentsContract.Document.COLUMN_DOCUMENT_ID }, null, null, null);
while (c.moveToNext()) {
final String documentId = c.getString(0);
final Uri documentUri = DocumentsContract.buildDocumentUriUsingTree(self,
documentId);
results.add(documentUri);
}
} catch (Exception e) {
Log.w(TAG, "Failed query: " + e);
} finally {
closeQuietly(c);
}
return results.toArray(new Uri[results.size()]);
}
@Override
public Cursor queryChildDocuments(String parentDocumentId, String[] projection, String sortOrder) {
ensureServiceBound();
List<Map<String, Serializable>> files;
try {
files = mService.loadFiles(parentDocumentId);
} catch (RemoteException e) {
return null;
}
final MatrixCursor result = new MatrixCursor(projection == null ? DEFAULT_DOCUMENT_PROJECTION : projection);
// Allow receiving notification on create / delete
result.setNotificationUri(getContext().getContentResolver(),
DocumentsContract.buildDocumentUri(AUTHORITY, parentDocumentId));
for (Map<String, Serializable> file : files) {
includeFile(result, file);
}
return result;
}
@SuppressLint("NewApi")
public static String uriToPath(Context context, Uri uri) {
boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
Log.d("maxiee", "docID:" + docId);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
final String selection = "_id=?";
final String[] selectionArgs = new String[] {split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
} else if ("content".equalsIgnoreCase(uri.getScheme())){
return getDataColumn(context, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Uri findChildDocument(ContentResolver contentResolver, Uri uri, String displayName) {
String[] projection = {DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME};
Uri childUri = DocumentsContract.buildChildDocumentsUriUsingTree(uri,
DocumentsContract.getDocumentId(uri));
Cursor cursor = contentResolver.query(childUri, projection, null, null, null);
try {
while (cursor.moveToNext()) {
if (displayName.equals(cursor.getString(1))) {
return DocumentsContract.buildDocumentUriUsingTree(uri, cursor.getString(0));
}
}
} finally {
cursor.close();
}
return null;
}
private Object getDocumentValue(CachedPathInfo cpi, String columnName)
{
switch (columnName)
{
case DocumentsContract.Document.COLUMN_DISPLAY_NAME:
return cpi.getName();
case DocumentsContract.Document.COLUMN_DOCUMENT_ID:
Location tmp = _location.copy();
tmp.setCurrentPath(cpi.getPath());
return getDocumentIdFromLocation(tmp);
case DocumentsContract.Document.COLUMN_FLAGS:
return getDocumentFlags(cpi);
//icon is null
//case DocumentsContract.Document.COLUMN_ICON:
case DocumentsContract.Document.COLUMN_LAST_MODIFIED:
return cpi.getModificationDate().getTime();
case DocumentsContract.Document.COLUMN_MIME_TYPE:
return getDocumentMimeType(cpi);
case DocumentsContract.Document.COLUMN_SIZE:
return cpi.getSize();
//summary is null
//case DocumentsContract.Document.COLUMN_SUMMARY:
}
return null;
}
@Override
public String getDocumentType(String documentId) throws FileNotFoundException
{
try
{
Location loc = getLocationsManager().getLocation(getLocationUriFromDocumentId(documentId));
return LoadPathInfoObservable.create(loc).map(cpi -> cpi.isFile() ?
FileOpsService.getMimeTypeFromExtension(
getContext(),
new StringPathUtil(cpi.getName()).getFileExtension()
) : DocumentsContract.Document.MIME_TYPE_DIR
).
subscribeOn(Schedulers.io()).
blockingGet();
}
catch (Exception e)
{
Logger.log(e);
throw new IllegalArgumentException("Wrong document uri", e);
}
}
/**
* @param data
* @return 图片路径
*/
public static String handleImageOnKitKat(Intent data) {
String imagePath = "";
Log.i(TAG, "handleImageOnKitKat: ");
Uri uri = data.getData();
if (DocumentsContract.isDocumentUri(MyApplication.getContext(), uri)) {
//如果是document类型的uri,则通过document id处理
String docId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = docId.split(":")[1];//解析出数字格式的ID
String selection = MediaStore.Images.Media._ID + "=" + id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
imagePath = getImagePath(contentUri, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
//如果是content类型的uri,则使用普通的方式处理
imagePath = getImagePath(uri, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
//如果是file类型的uri,直接获取图片路径即可
imagePath = uri.getPath();
}
return imagePath;
}
@Override
public boolean exists() throws IOException
{
Cursor c = null;
try
{
c = _context.getContentResolver().query(_documentUri, new String[]{
DocumentsContract.Document.COLUMN_DOCUMENT_ID}, null, null, null);
return c != null && c.getCount() > 0;
}
catch (Exception e)
{
if(GlobalConfig.isDebug())
Logger.log(e);
}
finally
{
closeQuietly(c);
}
return false;
}
public static Uri[] listFiles(Context context, Uri self) {
final ContentResolver resolver = context.getContentResolver();
final Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(self,
DocumentsContract.getDocumentId(self));
final ArrayList<Uri> results = new ArrayList<Uri>();
Cursor c = null;
try {
c = resolver.query(childrenUri, new String[] {
DocumentsContract.Document.COLUMN_DOCUMENT_ID }, null, null, null);
while (c.moveToNext()) {
final String documentId = c.getString(0);
final Uri documentUri = DocumentsContract.buildDocumentUriUsingTree(self,
documentId);
results.add(documentUri);
}
} catch (Exception e) {
Log.w(TAG, "Failed query: " + e);
} finally {
closeQuietly(c);
}
return results.toArray(new Uri[results.size()]);
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private static String getKitKatPathFromMediaUri(Context context, Uri uri) {
String imagePath = "";
if (DocumentsContract.isDocumentUri(context, uri)) {
String docId = DocumentsContract.getDocumentId(uri);
if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
//Log.d(TAG, uri.toString());
String id = docId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=" + id;
imagePath = getImagePathFromMediaUri(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
//Log.d(TAG, uri.toString());
Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
Long.valueOf(docId));
imagePath = getImagePathFromMediaUri(context, contentUri, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
//Log.d(TAG, "content: " + uri.toString());
imagePath = getImagePathFromMediaUri(context, uri, null);
}
return imagePath;
}
private static String getPicturePathFromUriAboveApi19(Context context, Uri uri) {
String filePath = null;
if (DocumentsContract.isDocumentUri(context, uri)) {
// 如果是document类型的 uri, 则通过document id来进行处理
String documentId = DocumentsContract.getDocumentId(uri);
if (isMediaDocument(uri)) { // MediaProvider
// 使用':'分割
String id = documentId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=?";
String[] selectionArgs = {id};
filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
} else if (isDownloadsDocument(uri)) { // DownloadsProvider
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
filePath = getDataColumn(context, contentUri, null, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
// 如果是 content 类型的 Uri
filePath = getDataColumn(context, uri, null, null);
} else if ("file".equals(uri.getScheme())) {
// 如果是 file 类型的 Uri,直接获取图片对应的路径
filePath = uri.getPath();
}
return filePath;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == MEDIA_CHOOSER_REQUEST_CODE) {
if (resultCode == RESULT_OK && data != null) {
ArrayList<Uri> uris = extractImageUris(data);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
for (Uri uri : uris) {
if (DocumentsContract.isDocumentUri(this, uri)) {
getContentResolver().takePersistableUriPermission(uri, takeFlags);
}
}
}
showImages(uris);
} else {
setResult(RESULT_CANCELED);
finish();
}
}
}
@SuppressLint("NewApi")
private static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
@TargetApi(Build.VERSION_CODES.KITKAT)
public String getDocPath(Uri uri) {
String wholeID = DocumentsContract.getDocumentId(uri);
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = mActivity.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel,
new String[]{id}, null);
String filePath = null;
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static String getVolumeIdFromTreeUri(final Uri treeUri) {
final String docId = DocumentsContract.getTreeDocumentId(treeUri);
final String[] split = docId.split(":");
if (split.length > 0) return split[0];
else return null;
}
/**
* 适配api19及以上,根据uri获取图片的绝对路径
*
* @param context 上下文对象
* @param uri 图片的Uri
* @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
*/
@SuppressLint("NewApi")
private static String getRealPathFromUriAboveApi19(Context context, Uri uri) {
String filePath = null;
if (DocumentsContract.isDocumentUri(context, uri)) {
// 如果是document类型的 uri, 则通过document id来进行处理
String documentId = DocumentsContract.getDocumentId(uri);
if (isMediaDocument(uri)) { // MediaProvider
// 使用':'分割
String id = documentId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=?";
String[] selectionArgs = {id};
filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
} else if (isDownloadsDocument(uri)) { // DownloadsProvider
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
filePath = getDataColumn(context, contentUri, null, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
// 如果是 content 类型的 Uri
filePath = getDataColumn(context, uri, null, null);
} else if ("file".equals(uri.getScheme())) {
// 如果是 file 类型的 Uri,直接获取图片对应的路径
filePath = uri.getPath();
}
return filePath;
}
@SuppressLint("NewApi")
public static void saveAvatar(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
startQuery(context, contentUri, selection, selectionArgs);
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
startQuery(context, uri, null, null);
}
}
/**
* Get the volume ID from the tree URI.
*
* @param treeUri The tree URI.
* @return The volume ID.
*/
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private static String getVolumeIdFromTreeUri(final Uri treeUri) {
final String docId = DocumentsContract.getTreeDocumentId(treeUri);
final String[] split = docId.split(":");
if (split.length > 0) {
return split[0];
}
else {
return null;
}
}
@NonNull
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static String getDocumentPathFromTreeUri(@NonNull Uri treeUri) {
final String docId = DocumentsContract.getTreeDocumentId(treeUri);
final String[] split = docId.split(":");
if ((split.length >= 2) && (split[1] != null)) return split[1];
else return File.separator;
}
/**
* Get the volume ID from the tree URI.
*
* @param treeUri The tree URI.
* @return The volume ID.
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static String getVolumeIdFromTreeUri(final Uri treeUri) {
final String docId = DocumentsContract.getTreeDocumentId(treeUri);
final String[] split = docId.split(":");
if (split.length > 0) {
return split[0];
} else {
return null;
}
}
/**
* Get the document path (relative to volume name) for a tree URI (LOLLIPOP).
*
* @param treeUri The tree URI.
* @return the document path.
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static String getDocumentPathFromTreeUri(final Uri treeUri) {
final String docId = DocumentsContract.getTreeDocumentId(treeUri);
final String[] split = docId.split(":");
if ((split.length >= 2) && (split[1] != null)) {
return split[1];
} else {
return File.separator;
}
}
/**
* Get the document path (relative to volume name) for a tree URI (LOLLIPOP).
*
* @param treeUri The tree URI.
* @return the document path.
*/
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private static String getDocumentPathFromTreeUri(final Uri treeUri) {
final String docId = DocumentsContract.getTreeDocumentId(treeUri);
final String[] split = docId.split(":");
if ((split.length >= 2) && (split[1] != null)) {
return split[1];
}
else {
return File.separator;
}
}
public static String getPathWithoutRoot(Uri docUri) {
String path = DocumentsContract.getTreeDocumentId(docUri);
int indexOfLastColon = path.lastIndexOf(':');
if (indexOfLastColon == -1)
throw new IllegalArgumentException("Given uri does not contain a colon: " + docUri);
return path.substring(indexOfLastColon + 1);
}
public static Uri buildChildDocumentUri(Uri directoryUri, String childDisplayName) {
if (!isTreeUri(directoryUri))
throw new IllegalArgumentException("directoryUri must be a tree uri");
String rootPath = getRootForPath(directoryUri);
String directoryPath = getPathWithoutRoot(directoryUri);
String childPath = rootPath + ":" + directoryPath + "/" + FileUtils.buildValidFatFilename(childDisplayName);
return DocumentsContract.buildDocumentUriUsingTree(directoryUri, childPath);
}
public static Uri createFile(Context context, Uri self, String mimeType,
String displayName) {
try {
return DocumentsContract.createDocument(context.getContentResolver(), self, mimeType,
displayName);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}