ก่อนอื่นคุณต้องเพิ่มผู้ให้บริการลงใน AndroidManifest ของคุณ
  <application
    ...>
    <activity>
    .... 
    </activity>
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.your.package.fileProvider"
        android:grantUriPermissions="true"
        android:exported="false">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
  </application>
ตอนนี้สร้างไฟล์ในโฟลเดอร์ทรัพยากร xml (หากใช้ android studio คุณสามารถกด Alt + Enter หลังจากไฮไลต์ file_paths และเลือกสร้างตัวเลือกทรัพยากร xml)
ถัดไปในไฟล์ file_paths
<?xml version="1.0" encoding="utf-8"?>
<paths>
  <external-path path="Android/data/com.your.package/" name="files_root" />
  <external-path path="." name="external_storage_root" />
</paths>
ตัวอย่างนี้ใช้สำหรับพา ธ ภายนอกคุณสามารถอ้างอิงได้ที่นี่เพื่อดูตัวเลือกเพิ่มเติม นี่จะช่วยให้คุณสามารถแชร์ไฟล์ที่อยู่ในโฟลเดอร์นั้นและโฟลเดอร์ย่อย
ตอนนี้สิ่งที่เหลือคือการสร้างความตั้งใจดังนี้
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    String ext = newFile.getName().substring(newFile.getName().lastIndexOf(".") + 1);
    String type = mime.getMimeTypeFromExtension(ext);
    try {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(getContext(), "com.your.package.fileProvider", newFile);
            intent.setDataAndType(contentUri, type);
        } else {
            intent.setDataAndType(Uri.fromFile(newFile), type);
        }
        startActivityForResult(intent, ACTIVITY_VIEW_ATTACHMENT);
    } catch (ActivityNotFoundException anfe) {
        Toast.makeText(getContext(), "No activity found to open this attachment.", Toast.LENGTH_LONG).show();
    }
แก้ไข : ฉันเพิ่มโฟลเดอร์รากของ sd card ใน file_paths ฉันทดสอบโค้ดนี้แล้วและใช้งานได้