पसंद के मुताबिक दस्तावेज़ देने वाला बनाएं

अगर आपको ऐसा ऐप्लिकेशन बनाना है जो फ़ाइलों के लिए स्टोरेज सेवाएं उपलब्ध कराता है (जैसे कि क्लाउड सेव सेवा), तो स्टोरेज ऐक्सेस फ़्रेमवर्क (एसएएफ़) की मदद से अपनी फ़ाइलें उपलब्ध कराई जा सकती हैं. इसके लिए, आपको पसंद के मुताबिक दस्तावेज़ उपलब्ध कराने वाली सेवा बनानी होगी. इस पेज पर, कस्टम दस्तावेज़ प्रोवाइडर बनाने का तरीका बताया गया है.

स्टोरेज ऐक्सेस फ़्रेमवर्क के काम करने के तरीके के बारे में ज़्यादा जानने के लिए, स्टोरेज ऐक्सेस फ़्रेमवर्क की खास जानकारी देखें.

मेनिफ़ेस्ट

कस्टम दस्तावेज़ की सेवा देने वाली कंपनी को लागू करने के लिए, अपने ऐप्लिकेशन के मेनिफ़ेस्ट में यह जोड़ें:

  • एपीआई लेवल 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 की अनुमति. डिफ़ॉल्ट रूप से, सेवा देने वाली कंपनी सभी के लिए उपलब्ध होती है. यह अनुमति देने पर, सेवा देने वाली कंपनी सिर्फ़ सिस्टम को ऐक्सेस कर पाती है. यह पाबंदी सुरक्षा के लिहाज़ से ज़रूरी है.
  • एक इंटेंट फ़िल्टर, जिसमें 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 और इससे पहले के वर्शन वाले डिवाइसों के लिए सहायता

ACTION_OPEN_DOCUMENT इंटेंट, सिर्फ़ Android 4.4 और इसके बाद के वर्शन वाले डिवाइसों पर उपलब्ध है. अगर आपको अपने ऐप्लिकेशन में ACTION_GET_CONTENT की सुविधा देनी है, ताकि Android 4.3 और इससे पहले के वर्शन वाले डिवाइसों पर भी यह काम कर सके, तो आपको Android 4.4 या इसके बाद के वर्शन वाले डिवाइसों के लिए, अपने मेनिफ़ेस्ट में ACTION_GET_CONTENT इंटेंट फ़िल्टर को बंद करना होगा. दस्तावेज़ उपलब्ध कराने वाली सेवा और ACTION_GET_CONTENT को एक-दूसरे से अलग माना जाना चाहिए. अगर आपका ऐप्लिकेशन दोनों को एक साथ इस्तेमाल करता है, तो वह सिस्टम पिकर यूज़र इंटरफ़ेस (यूआई) में दो बार दिखता है. इससे, सेव किए गए डेटा को ऐक्सेस करने के दो अलग-अलग तरीके मिलते हैं. इससे उपयोगकर्ताओं को भ्रम हो सकता है.

Android 4.4 या इसके बाद के वर्शन वाले डिवाइसों के लिए, ACTION_GET_CONTENT इंटेंट फ़िल्टर को बंद करने का सुझाया गया तरीका यहां दिया गया है:

  1. res/values/ में मौजूद अपनी bool.xml रिसॉर्स फ़ाइल में, यह लाइन जोड़ें:
    <bool name="atMostJellyBeanMR2">true</bool>
  2. res/values-v19/ में मौजूद अपनी bool.xml रिसॉर्स फ़ाइल में, यह लाइन जोड़ें:
    <bool name="atMostJellyBeanMR2">false</bool>
  3. वर्शन 4.4 (एपीआई लेवल 19) और इसके बाद के वर्शन के लिए, ACTION_GET_CONTENT इंटेंट फ़िल्टर को बंद करने के लिए, ऐक्टिविटी का दूसरा नाम जोड़ें. उदाहरण के लिए:
    <!-- 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>

समझौते

आम तौर पर, जब कस्टम कॉन्टेंट देने वाला कोई ऐप्लिकेशन बनाया जाता है, तो उसमें कॉन्ट्रैक्ट क्लास लागू करना एक ज़रूरी काम होता है. इसके बारे में, कॉन्टेंट देने वाले ऐप्लिकेशन की डेवलपर गाइड में बताया गया है. कॉन्ट्रैक्ट क्लास एक public final क्लास होती है. इसमें यूआरआई, कॉलम के नाम, एमआईएमई टाइप, और प्रोवाइडर से जुड़े अन्य मेटाडेटा के लिए कॉन्स्टेंट डेफ़िनिशन शामिल होती हैं. 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;
}

अगर आपका दस्तावेज़ प्रोवाइडर, रूट के डाइनैमिक सेट से कनेक्ट होता है, तो दस्तावेज़ के यूज़र इंटरफ़ेस (यूआई) को अपडेट किया जा सकता है. इससे, उन बदलावों के साथ सिंक किया जा सकता है जो 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 में तय किए गए कॉलम का इस्तेमाल करके, बताई गई फ़ाइल पर ले जाता है.

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 का इस्तेमाल कर सकते हैं. जब उपयोगकर्ता किसी फ़ाइल को चुनता है, तो सिस्टम इस तरीके को कॉल करता है. इसके बाद, क्लाइंट ऐप्लिकेशन 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() तरीके लागू करें. इन तरीकों से, ParcelFileDescriptor ऑब्जेक्ट का एक जोड़ा बनाया जा सकता है. इसमें एक ऑब्जेक्ट को वापस किया जा सकता है और दूसरे को ParcelFileDescriptor.AutoCloseOutputStream या ParcelFileDescriptor.AutoCloseInputStream के ज़रिए भेजा जा सकता है.

हाल ही के दस्तावेज़ों और खोज के लिए सहायता

दस्तावेज़ उपलब्ध कराने वाले ऐप्लिकेशन के रूट में, हाल ही में बदलाव किए गए दस्तावेज़ों की सूची दी जा सकती है. इसके लिए, आपको 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 कोड सैंपल डाउनलोड करें.

दस्तावेज़ बनाने में मदद करना

क्लाइंट ऐप्लिकेशन को अपने दस्तावेज़ प्रोवाइडर में फ़ाइलें बनाने की अनुमति दी जा सकती है. अगर कोई क्लाइंट ऐप्लिकेशन ACTION_CREATE_DOCUMENT इंटेंट भेजता है, तो दस्तावेज़ की सेवा देने वाला ऐप्लिकेशन, उस क्लाइंट ऐप्लिकेशन को अपने अंदर नए दस्तावेज़ बनाने की अनुमति दे सकता है.

दस्तावेज़ बनाने की सुविधा देने के लिए, आपके रूट में FLAG_SUPPORTS_CREATE फ़्लैग होना चाहिए. जिन डायरेक्ट्री में नई फ़ाइलें बनाई जा सकती हैं उनमें FLAG_DIR_SUPPORTS_CREATE फ़्लैग होना चाहिए.

दस्तावेज़ उपलब्ध कराने वाली कंपनी को भी 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 कॉलम में एक फ़्लैग जोड़ें. इससे पता चलेगा कि यह सुविधा काम करती है. आपको DocumentsProvider क्लास के लिए, उससे जुड़े तरीके को भी लागू करना होगा.

यहां दी गई टेबल में, COLUMN_FLAGS फ़्लैग और DocumentsProvider तरीके के बारे में बताया गया है. दस्तावेज़ उपलब्ध कराने वाली सेवा को खास सुविधाएं दिखाने के लिए, इन्हें लागू करना ज़रूरी है.

सुविधा झंडा तरीका
कोई फ़ाइल हटाएं FLAG_SUPPORTS_DELETE deleteDocument()
फ़ाइल का नाम बदलें FLAG_SUPPORTS_RENAME renameDocument()
दस्तावेज़ की सेवा देने वाली कंपनी के अंदर, किसी फ़ाइल को नई पैरंट डायरेक्ट्री में कॉपी करना FLAG_SUPPORTS_COPY copyDocument()
दस्तावेज़ की सेवा देने वाली कंपनी के अंदर, किसी फ़ाइल को एक डायरेक्ट्री से दूसरी डायरेक्ट्री में ले जाना FLAG_SUPPORTS_MOVE moveDocument()
किसी फ़ाइल को उसकी पैरंट डायरेक्ट्री से हटाना FLAG_SUPPORTS_REMOVE removeDocument()

वर्चुअल फ़ाइलों और अन्य फ़ाइल फ़ॉर्मैट के लिए सहायता

वर्चुअल फ़ाइलें, Android 7.0 (एपीआई लेवल 24) में पेश की गई एक सुविधा है. इसकी मदद से, दस्तावेज़ उपलब्ध कराने वाली कंपनियां, उन फ़ाइलों को देखने का ऐक्सेस दे सकती हैं जिनका सीधा बाइट कोड नहीं होता. अन्य ऐप्लिकेशन को वर्चुअल फ़ाइलें देखने की अनुमति देने के लिए, दस्तावेज़ उपलब्ध कराने वाली कंपनी को वर्चुअल फ़ाइलों के लिए, खोली जा सकने वाली फ़ाइल का कोई दूसरा फ़ॉर्मैट उपलब्ध कराना होगा.

उदाहरण के लिए, मान लें कि दस्तावेज़ उपलब्ध कराने वाली सेवा के पास कोई ऐसी फ़ाइल है जिसका फ़ॉर्मैट अन्य ऐप्लिकेशन सीधे तौर पर नहीं खोल सकते. यह फ़ाइल, वर्चुअल फ़ाइल होती है. जब कोई क्लाइंट ऐप्लिकेशन, CATEGORY_OPENABLE कैटगरी के बिना ACTION_VIEW इंटेंट भेजता है, तो उपयोगकर्ता दस्तावेज़ की सेवा देने वाली कंपनी के ऐप्लिकेशन में, इन वर्चुअल फ़ाइलों को देखने के लिए चुन सकते हैं. इसके बाद, दस्तावेज़ उपलब्ध कराने वाला ऐप्लिकेशन, वर्चुअल फ़ाइल को किसी दूसरे फ़ाइल फ़ॉर्मैट में दिखाता है. हालांकि, यह फ़ाइल फ़ॉर्मैट ऐसा होता है जिसे खोला जा सकता है, जैसे कि इमेज. इसके बाद, क्लाइंट ऐप्लिकेशन उपयोगकर्ता के लिए वर्चुअल फ़ाइल खोल सकता है, ताकि वह उसे देख सके.

यह बताने के लिए कि प्रोवाइडर में मौजूद कोई दस्तावेज़ वर्चुअल है, आपको FLAG_VIRTUAL_DOCUMENT फ़्लैग को उस फ़ाइल में जोड़ना होगा जो queryDocument() तरीके से मिली है. यह फ़्लैग, क्लाइंट ऐप्लिकेशन को सूचना देता है कि फ़ाइल में सीधे तौर पर बाइट कोड नहीं है और इसे सीधे तौर पर नहीं खोला जा सकता.

अगर आपने दस्तावेज़ उपलब्ध कराने वाली सेवा में मौजूद किसी फ़ाइल को वर्चुअल के तौर पर सेट किया है, तो हमारा सुझाव है कि आप उसे किसी दूसरे एमआईएमई टाइप में उपलब्ध कराएं. जैसे, इमेज या PDF. दस्तावेज़ उपलब्ध कराने वाली सेवा, वर्चुअल फ़ाइल को देखने के लिए, getDocumentStreamTypes() तरीके को बदलकर, वैकल्पिक एमआईएमई टाइप का एलान करती है. जब क्लाइंट ऐप्लिकेशन getStreamTypes(android.net.Uri, java.lang.String) तरीके को कॉल करते हैं, तो सिस्टम दस्तावेज़ उपलब्ध कराने वाली सेवा के getDocumentStreamTypes() तरीके को कॉल करता है. इसके बाद, getDocumentStreamTypes() वाला तरीका, अन्य एमआईएमई टाइप का कलेक्शन दिखाता है. ये ऐसे एमआईएमई टाइप होते हैं जो दस्तावेज़ उपलब्ध कराने वाली सेवा के साथ काम करते हैं.

जब क्लाइंट यह तय कर लेता है कि दस्तावेज़ की सेवा देने वाली कंपनी, दस्तावेज़ को देखे जा सकने वाले फ़ाइल फ़ॉर्मैट में उपलब्ध करा सकती है, तो क्लाइंट ऐप्लिकेशन openTypedAssetFileDescriptor() तरीके को कॉल करता है. यह तरीका, दस्तावेज़ की सेवा देने वाली कंपनी के 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 याद है? हम इसका इस्तेमाल, इस यूआरआई को बनाने के लिए कर रहे हैं. यहां दिया गया स्निपेट, सिस्टम को यह निर्देश देता है कि जब भी उपयोगकर्ता के लॉगिन की स्थिति में बदलाव हो, तब आपके दस्तावेज़ की सेवा देने वाली कंपनी के रूट से क्वेरी की जाए. अगर उपयोगकर्ता ने लॉग इन नहीं किया है, तो queryRoots() को कॉल करने पर, खाली कर्सर दिखता है. जैसा कि ऊपर दिखाया गया है. इससे यह पक्का होता है कि सेवा देने वाली कंपनी के दस्तावेज़ सिर्फ़ तब उपलब्ध हों, जब उपयोगकर्ता ने सेवा देने वाली कंपनी के खाते में लॉग इन किया हो.

Kotlin

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

Java

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

इस पेज से जुड़े सैंपल कोड के लिए, यहां जाएं:

इस पेज से जुड़े वीडियो देखने के लिए, यहां जाएं:

इससे जुड़ी ज़्यादा जानकारी के लिए, इन्हें देखें: