יצירת ספק מסמכים בהתאמה אישית

אם אתם מפתחים אפליקציה שמספקת שירותי אחסון לקבצים (כמו שירות שמירה בענן), אתם יכולים להפוך את הקבצים לזמינים דרך Storage Access Framework‏ (SAF) על ידי כתיבת ספק מסמכים בהתאמה אישית. בדף הזה מוסבר איך ליצור ספק מסמכים בהתאמה אישית.

למידע נוסף על אופן הפעולה של Storage Access Framework, עיינו בסקירה הכללית על Storage Access Framework.

מניפסט

כדי להטמיע ספק מסמכים בהתאמה אישית, מוסיפים את הקוד הבא למניפסט של האפליקציה:

  • רמת API לטירגוט של 19 ומעלה.
  • רכיב <provider> שמצהיר על ספק האחסון המותאם אישית.
  • המאפיין android:name מוגדר לשם של מחלקת המשנה של DocumentsProvider, שהוא שם המחלקה, כולל שם החבילה:

    com.example.android.storageprovider.MyCloudProvider.

  • המאפיין android:authority, שהוא שם החבילה (בדוגמה הזו, com.example.android.storageprovider) בתוספת סוג הספק לניהול גישה (documents).
  • המאפיין android:exported מוגדר לערך "true". צריך לייצא את הספק כדי שאפליקציות אחרות יוכלו לראות אותו.
  • המאפיין android:grantUriPermissions מוגדר לערך "true". ההגדרה הזו מאפשרת למערכת לתת לאפליקציות אחרות גישה לתוכן של הספק שלכם. במאמר הרשאות קבועות מוסבר איך האפליקציות האחרות יכולות לשמור על הגישה שלהן לתוכן מהספק שלכם.
  • ההרשאה MANAGE_DOCUMENTS. כברירת מחדל, הספק זמין לכולם. הוספת ההרשאה הזו מגבילה את הספק למערכת. ההגבלה הזו חשובה מטעמי אבטחה.
  • מסנן Intent שכולל את הפעולה android.content.action.DOCUMENTS_PROVIDER, כדי שהספק יופיע בכלי לבחירת ספקים כשהמערכת מחפשת ספקים.

הנה קטעים ממניפסט לדוגמה שכולל ספק:

<manifest... >
    ...
    <uses-sdk
        android:minSdkVersion="19"
        android:targetSdkVersion="19" />
        ....
        <provider
            android:name="com.example.android.storageprovider.MyCloudProvider"
            android:authorities="com.example.android.storageprovider.documents"
            android:grantUriPermissions="true"
            android:exported="true"
            android:permission="android.permission.MANAGE_DOCUMENTS">
            <intent-filter>
                <action android:name="android.content.action.DOCUMENTS_PROVIDER" />
            </intent-filter>
        </provider>
    </application>

</manifest>

תמיכה במכשירים עם Android מגרסה 4.3 ומטה

ה-intent‏ ACTION_OPEN_DOCUMENT זמין רק במכשירים עם Android מגרסה 4.4 ואילך. אם רוצים שהאפליקציה תתמוך ב-ACTION_GET_CONTENT כדי להתאים למכשירים עם Android מגרסה 4.3 ומטה, צריך להשבית את מסנן ה-Intent של ACTION_GET_CONTENT במניפסט למכשירים עם Android מגרסה 4.4 ומעלה. ספק מסמכים ו-ACTION_GET_CONTENT צריכים להיחשב כבלעדיים הדדית. אם אתם תומכים בשניהם בו-זמנית, האפליקציה תופיע פעמיים בממשק המשתמש של כלי המערכת לבחירת מדיה, ותציע שתי דרכים שונות לגשת לנתונים ששמרתם. זה מבלבל את המשתמשים.

כך מומלץ להשבית את מסנן ה-Intent של ACTION_GET_CONTENT במכשירים עם Android מגרסה 4.4 ואילך:

  1. בקובץ המשאבים bool.xml, בקטע res/values/, מוסיפים את השורה הבאה:
    <bool name="atMostJellyBeanMR2">true</bool>
  2. בקובץ המשאבים bool.xml, בקטע res/values-v19/, מוסיפים את השורה הבאה:
    <bool name="atMostJellyBeanMR2">false</bool>
  3. מוסיפים שם חלופי לפעילות כדי להשבית את מסנן ה-Intent של ACTION_GET_CONTENT בגרסאות 4.4 (רמת API‏ 19) ומעלה. לדוגמה:
    <!-- This activity alias is added so that GET_CONTENT intent-filter
         can be disabled for builds on API level 19 and higher. -->
    <activity-alias android:name="com.android.example.app.MyPicker"
            android:targetActivity="com.android.example.app.MyActivity"
            ...
            android:enabled="@bool/atMostJellyBeanMR2">
        <intent-filter>
            <action android:name="android.intent.action.GET_CONTENT" />
            <category android:name="android.intent.category.OPENABLE" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="image/*" />
            <data android:mimeType="video/*" />
        </intent-filter>
    </activity-alias>

חוזים

בדרך כלל, כשכותבים ספק מותאם אישית לניהול גישה, אחת מהמשימות היא להטמיע מחלקות של ערכים קבועים (contract classes), כמו שמתואר במדריך למפתחים בנושא ספקים לניהול גישה. מחלקה של ערכים קבועים היא מחלקה של public final שמכילה הגדרות קבועות לכתובות ה-URI, לשמות העמודות, לסוגי ה-MIME ולמטא-נתונים אחרים שקשורים לספק. ה-SAF מספק את המחלקות האלה של ערכים קבועים, כך שאתם לא צריכים לכתוב אותן בעצמכם:

לדוגמה, אלה העמודות שאתם יכולים להחזיר בסמן כשספק המסמכים שלכם נשאל לגבי מסמכים או לגבי הרמה הבסיסית:

Kotlin

private val DEFAULT_ROOT_PROJECTION: Array<String> = arrayOf(
        DocumentsContract.Root.COLUMN_ROOT_ID,
        DocumentsContract.Root.COLUMN_MIME_TYPES,
        DocumentsContract.Root.COLUMN_FLAGS,
        DocumentsContract.Root.COLUMN_ICON,
        DocumentsContract.Root.COLUMN_TITLE,
        DocumentsContract.Root.COLUMN_SUMMARY,
        DocumentsContract.Root.COLUMN_DOCUMENT_ID,
        DocumentsContract.Root.COLUMN_AVAILABLE_BYTES
)
private val DEFAULT_DOCUMENT_PROJECTION: Array<String> = arrayOf(
        DocumentsContract.Document.COLUMN_DOCUMENT_ID,
        DocumentsContract.Document.COLUMN_MIME_TYPE,
        DocumentsContract.Document.COLUMN_DISPLAY_NAME,
        DocumentsContract.Document.COLUMN_LAST_MODIFIED,
        DocumentsContract.Document.COLUMN_FLAGS,
        DocumentsContract.Document.COLUMN_SIZE
)

Java

private static final String[] DEFAULT_ROOT_PROJECTION =
        new String[]{Root.COLUMN_ROOT_ID, Root.COLUMN_MIME_TYPES,
        Root.COLUMN_FLAGS, Root.COLUMN_ICON, Root.COLUMN_TITLE,
        Root.COLUMN_SUMMARY, Root.COLUMN_DOCUMENT_ID,
        Root.COLUMN_AVAILABLE_BYTES,};
private static final String[] DEFAULT_DOCUMENT_PROJECTION = new
        String[]{Document.COLUMN_DOCUMENT_ID, Document.COLUMN_MIME_TYPE,
        Document.COLUMN_DISPLAY_NAME, Document.COLUMN_LAST_MODIFIED,
        Document.COLUMN_FLAGS, Document.COLUMN_SIZE,};

הסמן של הרמה הבסיסית צריך לכלול עמודות חובה מסוימות. העמודות שיופיעו הן:

הסמן של המסמכים צריך לכלול את העמודות הנדרשות הבאות:

יצירת מחלקת משנה של DocumentsProvider

השלב הבא בכתיבת ספק מסמכים בהתאמה אישית הוא ליצור מחלקת משנה של המחלקה המופשטת DocumentsProvider. צריך להטמיע לפחות את השיטות הבאות:

אלה השיטות היחידות שאתם חייבים להטמיע, אבל יש עוד הרבה שיטות שאולי תרצו להטמיע. פרטים נוספים מופיעים בכתובת DocumentsProvider.

הגדרת שורש

ההטמעה של queryRoots() צריכה להחזיר Cursor שמצביע על כל תיקיות השורש של ספק המסמכים, באמצעות עמודות שמוגדרות ב-DocumentsContract.Root.

בקטע הקוד הבא, הפרמטר projection מייצג את השדות הספציפיים שהמבצע של הקריאה החוזרת רוצה לקבל בחזרה. קטע הקוד יוצר סמן חדש ומוסיף לו שורה אחת – שורש אחד, ספרייה ברמה העליונה, כמו "הורדות" או "תמונות". לרוב הספקים יש רק שורש אחד. יכול להיות שיש לכם יותר מכתובת אחת, למשל אם יש לכם כמה חשבונות משתמשים. במקרה כזה, פשוט מוסיפים שורה שנייה לסמן.

Kotlin

override fun queryRoots(projection: Array<out String>?): Cursor {
    // Use a MatrixCursor to build a cursor
    // with either the requested fields, or the default
    // projection if "projection" is null.
    val result = MatrixCursor(resolveRootProjection(projection))

    // If user is not logged in, return an empty root cursor.  This removes our
    // provider from the list entirely.
    if (!isUserLoggedIn()) {
        return result
    }

    // It's possible to have multiple roots (e.g. for multiple accounts in the
    // same app) -- just add multiple cursor rows.
    result.newRow().apply {
        add(DocumentsContract.Root.COLUMN_ROOT_ID, ROOT)

        // You can provide an optional summary, which helps distinguish roots
        // with the same title. You can also use this field for displaying an
        // user account name.
        add(DocumentsContract.Root.COLUMN_SUMMARY, context.getString(R.string.root_summary))

        // FLAG_SUPPORTS_CREATE means at least one directory under the root supports
        // creating documents. FLAG_SUPPORTS_RECENTS means your application's most
        // recently used documents will show up in the "Recents" category.
        // FLAG_SUPPORTS_SEARCH allows users to search all documents the application
        // shares.
        add(
            DocumentsContract.Root.COLUMN_FLAGS,
            DocumentsContract.Root.FLAG_SUPPORTS_CREATE or
                DocumentsContract.Root.FLAG_SUPPORTS_RECENTS or
                DocumentsContract.Root.FLAG_SUPPORTS_SEARCH
        )

        // COLUMN_TITLE is the root title (e.g. Gallery, Drive).
        add(DocumentsContract.Root.COLUMN_TITLE, context.getString(R.string.title))

        // This document id cannot change after it's shared.
        add(DocumentsContract.Root.COLUMN_DOCUMENT_ID, getDocIdForFile(baseDir))

        // The child MIME types are used to filter the roots and only present to the
        // user those roots that contain the desired type somewhere in their file hierarchy.
        add(DocumentsContract.Root.COLUMN_MIME_TYPES, getChildMimeTypes(baseDir))
        add(DocumentsContract.Root.COLUMN_AVAILABLE_BYTES, baseDir.freeSpace)
        add(DocumentsContract.Root.COLUMN_ICON, R.drawable.ic_launcher)
    }

    return result
}

Java

@Override
public Cursor queryRoots(String[] projection) throws FileNotFoundException {

    // Use a MatrixCursor to build a cursor
    // with either the requested fields, or the default
    // projection if "projection" is null.
    final MatrixCursor result =
            new MatrixCursor(resolveRootProjection(projection));

    // If user is not logged in, return an empty root cursor.  This removes our
    // provider from the list entirely.
    if (!isUserLoggedIn()) {
        return result;
    }

    // It's possible to have multiple roots (e.g. for multiple accounts in the
    // same app) -- just add multiple cursor rows.
    final MatrixCursor.RowBuilder row = result.newRow();
    row.add(Root.COLUMN_ROOT_ID, ROOT);

    // You can provide an optional summary, which helps distinguish roots
    // with the same title. You can also use this field for displaying an
    // user account name.
    row.add(Root.COLUMN_SUMMARY, getContext().getString(R.string.root_summary));

    // FLAG_SUPPORTS_CREATE means at least one directory under the root supports
    // creating documents. FLAG_SUPPORTS_RECENTS means your application's most
    // recently used documents will show up in the "Recents" category.
    // FLAG_SUPPORTS_SEARCH allows users to search all documents the application
    // shares.
    row.add(Root.COLUMN_FLAGS, Root.FLAG_SUPPORTS_CREATE |
            Root.FLAG_SUPPORTS_RECENTS |
            Root.FLAG_SUPPORTS_SEARCH);

    // COLUMN_TITLE is the root title (e.g. Gallery, Drive).
    row.add(Root.COLUMN_TITLE, getContext().getString(R.string.title));

    // This document id cannot change after it's shared.
    row.add(Root.COLUMN_DOCUMENT_ID, getDocIdForFile(baseDir));

    // The child MIME types are used to filter the roots and only present to the
    // user those roots that contain the desired type somewhere in their file hierarchy.
    row.add(Root.COLUMN_MIME_TYPES, getChildMimeTypes(baseDir));
    row.add(Root.COLUMN_AVAILABLE_BYTES, baseDir.getFreeSpace());
    row.add(Root.COLUMN_ICON, R.drawable.ic_launcher);

    return result;
}

אם ספק המסמכים מתחבר לקבוצה דינמית של שורשים – לדוגמה, להתקן USB שאפשר לנתק או לחשבון שהמשתמש יכול לצאת ממנו – אתם יכולים לעדכן את ממשק המשתמש של המסמך כדי להישאר מסונכרנים עם השינויים האלה באמצעות השיטה ContentResolver.notifyChange(), כפי שמוצג בקטע הקוד הבא.

Kotlin

val rootsUri: Uri = DocumentsContract.buildRootsUri(BuildConfig.DOCUMENTS_AUTHORITY)
context.contentResolver.notifyChange(rootsUri, null)

Java

Uri rootsUri = DocumentsContract.buildRootsUri(BuildConfig.DOCUMENTS_AUTHORITY);
context.getContentResolver().notifyChange(rootsUri, null);

הצגת רשימת המסמכים אצל הספק

ההטמעה של queryChildDocuments() צריכה להחזיר Cursor שמצביע על כל הקבצים בספרייה שצוינה, באמצעות עמודות שמוגדרות ב-DocumentsContract.Document.

המערכת קוראת לשיטה הזו כשהמשתמש בוחר את הרמה הבסיסית שלכם בממשק המשתמש של הכלי לבחירת קבצים. השיטה מאחזרת את הצאצאים של מזהה המסמך שצוין על ידי COLUMN_DOCUMENT_ID. המערכת קוראת לשיטה הזו בכל פעם שהמשתמש בוחר ספריית משנה בספק המסמכים.

הקטע הזה יוצר סמן חדש עם העמודות המבוקשות, ואז מוסיף לסמן מידע על כל צאצא מיידי בספריית האם. צאצא יכול להיות תמונה, ספרייה אחרת או כל קובץ אחר:

Kotlin

override fun queryChildDocuments(
        parentDocumentId: String?,
        projection: Array<out String>?,
        sortOrder: String?
): Cursor {
    return MatrixCursor(resolveDocumentProjection(projection)).apply {
        val parent: File = getFileForDocId(parentDocumentId)
        parent.listFiles()
                .forEach { file ->
                    includeFile(this, null, file)
                }
    }
}

Java

@Override
public Cursor queryChildDocuments(String parentDocumentId, String[] projection,
                              String sortOrder) throws FileNotFoundException {

    final MatrixCursor result = new
            MatrixCursor(resolveDocumentProjection(projection));
    final File parent = getFileForDocId(parentDocumentId);
    for (File file : parent.listFiles()) {
        // Adds the file's display name, MIME type, size, and so on.
        includeFile(result, null, file);
    }
    return result;
}

קבלת פרטי המסמך

ההטמעה של queryDocument() צריכה להחזיר Cursor שמצביע על הקובץ שצוין, באמצעות עמודות שמוגדרות ב-DocumentsContract.Document.

ה-method‏ queryDocument() מחזירה את אותו מידע שהועבר ב-queryChildDocuments(), אבל לקובץ ספציפי:

Kotlin

override fun queryDocument(documentId: String?, projection: Array<out String>?): Cursor {
    // Create a cursor with the requested projection, or the default projection.
    return MatrixCursor(resolveDocumentProjection(projection)).apply {
        includeFile(this, documentId, null)
    }
}

Java

@Override
public Cursor queryDocument(String documentId, String[] projection) throws
        FileNotFoundException {

    // Create a cursor with the requested projection, or the default projection.
    final MatrixCursor result = new
            MatrixCursor(resolveDocumentProjection(projection));
    includeFile(result, documentId, null);
    return result;
}

ספק המסמכים יכול גם לספק תמונות ממוזערות למסמך על ידי שינוי השיטה DocumentsProvider.openDocumentThumbnail() והוספת הדגל FLAG_SUPPORTS_THUMBNAIL לקבצים הנתמכים. בקטע הקוד הבא יש דוגמה לאיך אפשר להטמיע את DocumentsProvider.openDocumentThumbnail().

Kotlin

override fun openDocumentThumbnail(
        documentId: String?,
        sizeHint: Point?,
        signal: CancellationSignal?
): AssetFileDescriptor {
    val file = getThumbnailFileForDocId(documentId)
    val pfd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
    return AssetFileDescriptor(pfd, 0, AssetFileDescriptor.UNKNOWN_LENGTH)
}

Java

@Override
public AssetFileDescriptor openDocumentThumbnail(String documentId, Point sizeHint,
                                                     CancellationSignal signal)
        throws FileNotFoundException {

    final File file = getThumbnailFileForDocId(documentId);
    final ParcelFileDescriptor pfd =
        ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    return new AssetFileDescriptor(pfd, 0, AssetFileDescriptor.UNKNOWN_LENGTH);
}

זהירות: ספק מסמכים לא אמור להחזיר תמונות ממוזערות שגדולות יותר מפי שניים מהגודל שצוין בפרמטר sizeHint.

פתיחת מסמך

צריך להטמיע את openDocument() כדי להחזיר ParcelFileDescriptor שמייצג את הקובץ שצוין. אפליקציות אחרות יכולות להשתמש ב-ParcelFileDescriptor שמוחזר כדי להעביר נתונים בסטרימינג. המערכת קוראת ל-method הזו אחרי שהמשתמש בוחר קובץ, ואפליקציית הלקוח מבקשת גישה אליו באמצעות קריאה ל-openFileDescriptor(). לדוגמה:

Kotlin

override fun openDocument(
        documentId: String,
        mode: String,
        signal: CancellationSignal
): ParcelFileDescriptor {
    Log.v(TAG, "openDocument, mode: $mode")
    // It's OK to do network operations in this method to download the document,
    // as long as you periodically check the CancellationSignal. If you have an
    // extremely large file to transfer from the network, a better solution may
    // be pipes or sockets (see ParcelFileDescriptor for helper methods).

    val file: File = getFileForDocId(documentId)
    val accessMode: Int = ParcelFileDescriptor.parseMode(mode)

    val isWrite: Boolean = mode.contains("w")
    return if (isWrite) {
        val handler = Handler(context.mainLooper)
        // Attach a close listener if the document is opened in write mode.
        try {
            ParcelFileDescriptor.open(file, accessMode, handler) {
                // Update the file with the cloud server. The client is done writing.
                Log.i(TAG, "A file with id $documentId has been closed! Time to update the server.")
            }
        } catch (e: IOException) {
            throw FileNotFoundException(
                    "Failed to open document with id $documentId and mode $mode"
            )
        }
    } else {
        ParcelFileDescriptor.open(file, accessMode)
    }
}

Java

@Override
public ParcelFileDescriptor openDocument(final String documentId,
                                         final String mode,
                                         CancellationSignal signal) throws
        FileNotFoundException {
    Log.v(TAG, "openDocument, mode: " + mode);
    // It's OK to do network operations in this method to download the document,
    // as long as you periodically check the CancellationSignal. If you have an
    // extremely large file to transfer from the network, a better solution may
    // be pipes or sockets (see ParcelFileDescriptor for helper methods).

    final File file = getFileForDocId(documentId);
    final int accessMode = ParcelFileDescriptor.parseMode(mode);

    final boolean isWrite = (mode.indexOf('w') != -1);
    if(isWrite) {
        // Attach a close listener if the document is opened in write mode.
        try {
            Handler handler = new Handler(getContext().getMainLooper());
            return ParcelFileDescriptor.open(file, accessMode, handler,
                        new ParcelFileDescriptor.OnCloseListener() {
                @Override
                public void onClose(IOException e) {

                    // Update the file with the cloud server. The client is done
                    // writing.
                    Log.i(TAG, "A file with id " +
                    documentId + " has been closed! Time to " +
                    "update the server.");
                }

            });
        } catch (IOException e) {
            throw new FileNotFoundException("Failed to open document with id"
            + documentId + " and mode " + mode);
        }
    } else {
        return ParcelFileDescriptor.open(file, accessMode);
    }
}

אם ספק המסמכים מעביר קבצים בסטרימינג או מטפל במבני נתונים מורכבים, כדאי להטמיע את השיטות createReliablePipe() או createReliableSocketPair(). ה-methods האלה מאפשרות ליצור זוג אובייקטים מסוג ParcelFileDescriptor, להחזיר אחד מהם ולשלוח את השני באמצעות ParcelFileDescriptor.AutoCloseOutputStream או ParcelFileDescriptor.AutoCloseInputStream.

תמיכה במסמכים ובחיפושים מהזמן האחרון

כדי לספק רשימה של מסמכים ששונו לאחרונה ברמה הבסיסית (root) של ספק המסמכים, צריך לשנות את השיטה queryRecentDocuments() ולהחזיר את FLAG_SUPPORTS_RECENTS. קטע הקוד הבא מראה דוגמה להטמעה של השיטות queryRecentDocuments().

Kotlin

override fun queryRecentDocuments(rootId: String?, projection: Array<out String>?): Cursor {
    // This example implementation walks a
    // local file structure to find the most recently
    // modified files.  Other implementations might
    // include making a network call to query a
    // server.

    // Create a cursor with the requested projection, or the default projection.
    val result = MatrixCursor(resolveDocumentProjection(projection))

    val parent: File = getFileForDocId(rootId)

    // Create a queue to store the most recent documents,
    // which orders by last modified.
    val lastModifiedFiles = PriorityQueue(
            5,
            Comparator<File> { i, j ->
                Long.compare(i.lastModified(), j.lastModified())
            }
    )

    // Iterate through all files and directories
    // in the file structure under the root.  If
    // the file is more recent than the least
    // recently modified, add it to the queue,
    // limiting the number of results.
    val pending : MutableList<File> = mutableListOf()

    // Start by adding the parent to the list of files to be processed
    pending.add(parent)

    // Do while we still have unexamined files
    while (pending.isNotEmpty()) {
        // Take a file from the list of unprocessed files
        val file: File = pending.removeAt(0)
        if (file.isDirectory) {
            // If it's a directory, add all its children to the unprocessed list
            pending += file.listFiles()
        } else {
            // If it's a file, add it to the ordered queue.
            lastModifiedFiles.add(file)
        }
    }

    // Add the most recent files to the cursor,
    // not exceeding the max number of results.
    for (i in 0 until Math.min(MAX_LAST_MODIFIED + 1, lastModifiedFiles.size)) {
        val file: File = lastModifiedFiles.remove()
        includeFile(result, null, file)
    }
    return result
}

Java

@Override
public Cursor queryRecentDocuments(String rootId, String[] projection)
        throws FileNotFoundException {

    // This example implementation walks a
    // local file structure to find the most recently
    // modified files.  Other implementations might
    // include making a network call to query a
    // server.

    // Create a cursor with the requested projection, or the default projection.
    final MatrixCursor result =
        new MatrixCursor(resolveDocumentProjection(projection));

    final File parent = getFileForDocId(rootId);

    // Create a queue to store the most recent documents,
    // which orders by last modified.
    PriorityQueue lastModifiedFiles =
        new PriorityQueue(5, new Comparator() {

        public int compare(File i, File j) {
            return Long.compare(i.lastModified(), j.lastModified());
        }
    });

    // Iterate through all files and directories
    // in the file structure under the root.  If
    // the file is more recent than the least
    // recently modified, add it to the queue,
    // limiting the number of results.
    final LinkedList pending = new LinkedList();

    // Start by adding the parent to the list of files to be processed
    pending.add(parent);

    // Do while we still have unexamined files
    while (!pending.isEmpty()) {
        // Take a file from the list of unprocessed files
        final File file = pending.removeFirst();
        if (file.isDirectory()) {
            // If it's a directory, add all its children to the unprocessed list
            Collections.addAll(pending, file.listFiles());
        } else {
            // If it's a file, add it to the ordered queue.
            lastModifiedFiles.add(file);
        }
    }

    // Add the most recent files to the cursor,
    // not exceeding the max number of results.
    for (int i = 0; i < Math.min(MAX_LAST_MODIFIED + 1, lastModifiedFiles.size()); i++) {
        final File file = lastModifiedFiles.remove();
        includeFile(result, null, file);
    }
    return result;
}

כדי לקבל את הקוד המלא של קטע הקוד שלמעלה, אתם יכולים להוריד את דוגמת הקוד של StorageProvider.

יצירת מסמכי תמיכה

אתם יכולים לאפשר לאפליקציות לקוח ליצור קבצים בספק המסמכים שלכם. אם אפליקציית לקוח שולחת Intent מסוג ACTION_CREATE_DOCUMENT, ספק המסמכים יכול לאפשר לאפליקציית הלקוח הזו ליצור מסמכים חדשים בתוך ספק המסמכים.

כדי לתמוך ביצירת מסמכים, צריך להגדיר את הדגל FLAG_SUPPORTS_CREATE ברמה הבסיסית (root). בספריות שבהן אפשר ליצור קבצים חדשים צריך להיות הדגל FLAG_DIR_SUPPORTS_CREATE.

ספק המסמכים צריך גם להטמיע את ה-method createDocument(). כשמשתמש בוחר ספרייה בספק המסמכים כדי לשמור קובץ חדש, ספק המסמכים מקבל קריאה ל-createDocument(). בתוך ההטמעה של השיטה createDocument(), מחזירים COLUMN_DOCUMENT_ID חדש לקובץ. לאחר מכן, אפליקציית הלקוח יכולה להשתמש במזהה הזה כדי לקבל נקודת אחיזה לקובץ, ובסופו של דבר, להפעיל את openDocument() כדי לכתוב לקובץ החדש.

בקטע הקוד הבא אפשר לראות איך יוצרים קובץ חדש בתוך ספק מסמכים.

Kotlin

override fun createDocument(documentId: String?, mimeType: String?, displayName: String?): String {
    val parent: File = getFileForDocId(documentId)
    val file: File = try {
        File(parent.path, displayName).apply {
            createNewFile()
            setWritable(true)
            setReadable(true)
        }
    } catch (e: IOException) {
        throw FileNotFoundException(
                "Failed to create document with name $displayName and documentId $documentId"
        )
    }

    return getDocIdForFile(file)
}

Java

@Override
public String createDocument(String documentId, String mimeType, String displayName)
        throws FileNotFoundException {

    File parent = getFileForDocId(documentId);
    File file = new File(parent.getPath(), displayName);
    try {
        file.createNewFile();
        file.setWritable(true);
        file.setReadable(true);
    } catch (IOException e) {
        throw new FileNotFoundException("Failed to create document with name " +
                displayName +" and documentId " + documentId);
    }
    return getDocIdForFile(file);
}

כדי לקבל את הקוד המלא של קטע הקוד שלמעלה, אתם יכולים להוריד את דוגמת הקוד של StorageProvider.

תכונות לניהול מסמכי תמיכה

בנוסף לפתיחה, ליצירה ולהצגה של קבצים, ספק המסמכים יכול גם לאפשר לאפליקציות הלקוח לשנות את השם של הקבצים, להעתיק, להעביר ולמחוק אותם. כדי להוסיף פונקציונליות של ניהול מסמכים לספק המסמכים, צריך להוסיף דגל לעמודה COLUMN_FLAGS של המסמך כדי לציין את הפונקציונליות הנתמכת. צריך גם להטמיע את ה-method התואמת של המחלקה DocumentsProvider.

בטבלה הבאה מפורטים הדגל COLUMN_FLAGS וה-method‏ DocumentsProvider שספק המסמכים צריך להטמיע כדי לחשוף תכונות ספציפיות.

התכונה דגל שיטה
מחיקת קובץ FLAG_SUPPORTS_DELETE deleteDocument()
שינוי שם של קובץ FLAG_SUPPORTS_RENAME renameDocument()
העתקת קובץ לספריית אם חדשה בספק המסמכים FLAG_SUPPORTS_COPY copyDocument()
העברת קובץ מספרייה אחת לאחרת בתוך ספק המסמכים FLAG_SUPPORTS_MOVE moveDocument()
הסרת קובץ מספריית האם שלו FLAG_SUPPORTS_REMOVE removeDocument()

תמיכה בקבצים וירטואליים ובפורמטים חלופיים של קבצים

קבצים וירטואליים, תכונה שהושקה ב-Android 7.0 (רמת API ‏24), מאפשרת לספקי מסמכים לספק גישת צפייה לקבצים שאין להם ייצוג ישיר של קוד בייט. כדי לאפשר לאפליקציות אחרות להציג קבצים וירטואליים, ספק המסמכים צריך ליצור ייצוג חלופי של קובץ שניתן לפתוח עבור הקבצים הווירטואליים.

לדוגמה, נניח שספק מסמכים מכיל פורמט קובץ שאפליקציות אחרות לא יכולות לפתוח ישירות, כלומר קובץ וירטואלי. כשאפליקציית לקוח שולחת Intent מסוג ACTION_VIEW בלי הקטגוריה CATEGORY_OPENABLE, המשתמשים יכולים לבחור את הקבצים הווירטואליים האלה בתוך ספק המסמכים כדי לצפות בהם. לאחר מכן, ספק המסמכים מחזיר את הקובץ הווירטואלי בפורמט קובץ אחר שניתן לפתוח, כמו תמונה. אפליקציית הלקוח יכולה לפתוח את הקובץ הווירטואלי כדי שהמשתמש יוכל לצפות בו.

כדי להצהיר שמסמך בספק הוא וירטואלי, צריך להוסיף את הדגל FLAG_VIRTUAL_DOCUMENT לקובץ שמוחזר על ידי השיטה queryDocument(). הדגל הזה מתריע לאפליקציות הלקוח שלקובץ אין ייצוג ישיר של קוד בייטים ואי אפשר לפתוח אותו ישירות.

אם אתם מצהירים שקובץ בספק המסמכים שלכם הוא וירטואלי, מומלץ מאוד להפוך אותו לזמין בסוג MIME אחר, כמו תמונה או קובץ PDF. ספק המסמכים מצהיר על סוגי ה-MIME החלופיים שהוא תומך בהם לצפייה בקובץ וירטואלי, על ידי שינוי השיטה getDocumentStreamTypes(). כשאפליקציות לקוח קוראות ל-method‏ getStreamTypes(android.net.Uri, java.lang.String), המערכת קוראת ל-method‏ getDocumentStreamTypes() של ספק המסמכים. השיטה getDocumentStreamTypes() מחזירה מערך של סוגי MIME חלופיים שספק המסמכים תומך בהם בקובץ.

אחרי שהלקוח קובע שספק המסמכים יכול להפיק את המסמך בפורמט קובץ שניתן להציג, אפליקציית הלקוח קוראת ל-method‏ openTypedAssetFileDescriptor(), שקוראת באופן פנימי ל-method‏ openTypedDocument() של ספק המסמכים. ספק המסמכים מחזיר את הקובץ לאפליקציית הלקוח בפורמט הקובץ המבוקש.

בקטע הקוד הבא מוצגת הטמעה פשוטה של השיטות getDocumentStreamTypes() ו-openTypedDocument().

Kotlin

var SUPPORTED_MIME_TYPES : Array<String> = arrayOf("image/png", "image/jpg")
override fun openTypedDocument(
        documentId: String?,
        mimeTypeFilter: String,
        opts: Bundle?,
        signal: CancellationSignal?
): AssetFileDescriptor? {
    return try {
        // Determine which supported MIME type the client app requested.
        when(mimeTypeFilter) {
            "image/jpg" -> openJpgDocument(documentId)
            "image/png", "image/*", "*/*" -> openPngDocument(documentId)
            else -> throw IllegalArgumentException("Invalid mimeTypeFilter $mimeTypeFilter")
        }
    } catch (ex: Exception) {
        Log.e(TAG, ex.message)
        null
    }
}

override fun getDocumentStreamTypes(documentId: String, mimeTypeFilter: String): Array<String> {
    return when (mimeTypeFilter) {
        "*/*", "image/*" -> {
            // Return all supported MIME types if the client app
            // passes in '*/*' or 'image/*'.
            SUPPORTED_MIME_TYPES
        }
        else -> {
            // Filter the list of supported mime types to find a match.
            SUPPORTED_MIME_TYPES.filter { it == mimeTypeFilter }.toTypedArray()
        }
    }
}

Java

public static String[] SUPPORTED_MIME_TYPES = {"image/png", "image/jpg"};

@Override
public AssetFileDescriptor openTypedDocument(String documentId,
    String mimeTypeFilter,
    Bundle opts,
    CancellationSignal signal) {

    try {

        // Determine which supported MIME type the client app requested.
        if ("image/png".equals(mimeTypeFilter) ||
            "image/*".equals(mimeTypeFilter) ||
            "*/*".equals(mimeTypeFilter)) {

            // Return the file in the specified format.
            return openPngDocument(documentId);

        } else if ("image/jpg".equals(mimeTypeFilter)) {
            return openJpgDocument(documentId);
        } else {
            throw new IllegalArgumentException("Invalid mimeTypeFilter " + mimeTypeFilter);
        }

    } catch (Exception ex) {
        Log.e(TAG, ex.getMessage());
    } finally {
        return null;
    }
}

@Override
public String[] getDocumentStreamTypes(String documentId, String mimeTypeFilter) {

    // Return all supported MIME tyupes if the client app
    // passes in '*/*' or 'image/*'.
    if ("*/*".equals(mimeTypeFilter) ||
        "image/*".equals(mimeTypeFilter)) {
        return SUPPORTED_MIME_TYPES;
    }

    ArrayList requestedMimeTypes = new ArrayList&lt;&gt;();

    // Iterate over the list of supported mime types to find a match.
    for (int i=0; i &lt; SUPPORTED_MIME_TYPES.length; i++) {
        if (SUPPORTED_MIME_TYPES[i].equals(mimeTypeFilter)) {
            requestedMimeTypes.add(SUPPORTED_MIME_TYPES[i]);
        }
    }
    return (String[])requestedMimeTypes.toArray();
}

אבטחה

נניח שספק המסמכים שלכם הוא שירות אחסון בענן שמוגן באמצעות סיסמה, ואתם רוצים לוודא שהמשתמשים מחוברים לחשבון לפני שאתם מתחילים לשתף את הקבצים שלהם. מה האפליקציה צריכה לעשות אם המשתמש לא מחובר לחשבון? הפתרון הוא להחזיר אפס שורשים בהטמעה של queryRoots(). כלומר, סמן בסיס ריק:

Kotlin

override fun queryRoots(projection: Array<out String>): Cursor {
...
    // If user is not logged in, return an empty root cursor.  This removes our
    // provider from the list entirely.
    if (!isUserLoggedIn()) {
        return result
    }

Java

public Cursor queryRoots(String[] projection) throws FileNotFoundException {
...
    // If user is not logged in, return an empty root cursor.  This removes our
    // provider from the list entirely.
    if (!isUserLoggedIn()) {
        return result;
}

השלב השני הוא להתקשר אל getContentResolver().notifyChange(). זוכרים את DocumentsContract? אנחנו משתמשים בו כדי ליצור את ה-URI הזה. קטע הקוד הבא מורה למערכת לשלוח שאילתה לשורשים של ספק המסמכים בכל פעם שסטטוס ההתחברות של המשתמש משתנה. אם המשתמש לא מחובר, קריאה ל-queryRoots() מחזירה סמן ריק, כמו שמוצג למעלה. כך אפשר לוודא שהמסמכים של הספק זמינים רק אם המשתמש מחובר לספק.

Kotlin

private fun onLoginButtonClick() {
    loginOrLogout()
    getContentResolver().notifyChange(
        DocumentsContract.buildRootsUri(AUTHORITY),
        null
    )
}

Java

private void onLoginButtonClick() {
    loginOrLogout();
    getContentResolver().notifyChange(DocumentsContract
            .buildRootsUri(AUTHORITY), null);
}

לקוד לדוגמה שקשור לדף הזה, ראו:

סרטונים שקשורים לדף הזה:

מידע נוסף בנושא זמין במאמרים הבאים: