1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.support.v4.provider; 18 19 import android.content.ContentResolver; 20 import android.content.Context; 21 import android.database.Cursor; 22 import android.net.Uri; 23 import android.provider.DocumentsContract; 24 import android.util.Log; 25 26 import java.util.ArrayList; 27 28 class DocumentsContractApi21 { 29 private static final String TAG = "DocumentFile"; 30 31 public static Uri createFile(Context context, Uri self, String mimeType, 32 String displayName) { 33 return DocumentsContract.createDocument(context.getContentResolver(), self, mimeType, 34 displayName); 35 } 36 37 public static Uri createDirectory(Context context, Uri self, String displayName) { 38 return createFile(context, self, DocumentsContract.Document.MIME_TYPE_DIR, displayName); 39 } 40 41 public static Uri prepareTreeUri(Uri treeUri) { 42 return DocumentsContract.buildDocumentUriUsingTree(treeUri, 43 DocumentsContract.getTreeDocumentId(treeUri)); 44 } 45 46 public static Uri[] listFiles(Context context, Uri self) { 47 final ContentResolver resolver = context.getContentResolver(); 48 final Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(self, 49 DocumentsContract.getDocumentId(self)); 50 final ArrayList<Uri> results = new ArrayList<Uri>(); 51 52 Cursor c = null; 53 try { 54 c = resolver.query(childrenUri, new String[] { 55 DocumentsContract.Document.COLUMN_DOCUMENT_ID }, null, null, null); 56 while (c.moveToNext()) { 57 final String documentId = c.getString(0); 58 final Uri documentUri = DocumentsContract.buildDocumentUriUsingTree(self, 59 documentId); 60 results.add(documentUri); 61 } 62 } catch (Exception e) { 63 Log.w(TAG, "Failed query: " + e); 64 } finally { 65 closeQuietly(c); 66 } 67 68 return results.toArray(new Uri[results.size()]); 69 } 70 71 public static Uri renameTo(Context context, Uri self, String displayName) { 72 return DocumentsContract.renameDocument(context.getContentResolver(), self, displayName); 73 } 74 75 private static void closeQuietly(AutoCloseable closeable) { 76 if (closeable != null) { 77 try { 78 closeable.close(); 79 } catch (RuntimeException rethrown) { 80 throw rethrown; 81 } catch (Exception ignored) { 82 } 83 } 84 } 85 } 86