1

我正在將文件保存在內部存儲上。這只是有關對象的一些信息的.txt文件:來自內部存儲與內容提供商的Android Intent.ACTION_SEND

FileOutputStream outputStream; 
    String filename = "file.txt"; 

    File cacheDir = context.getCacheDir(); 
    File outFile = new File(cacheDir, filename); 
    outputStream = new FileOutputStream(outFile.getAbsolutePath()); 
    outputStream.write(myString.getBytes()); 
    outputStream.flush(); 
    outputStream.close(); 

然後我創建一個「shareIntent」共享此文件:

Uri notificationUri = Uri.parse("content://com.package.example/file.txt"); 
    Intent shareIntent = new Intent(Intent.ACTION_SEND); 
    shareIntent.putExtra(Intent.EXTRA_STREAM, notificationUri); 
    shareIntent.setType("text/plain"); 
    context.startActivity(Intent.createChooser(shareIntent, context.getResources().getText(R.string.chooser))); 

所選擇的應用程序現在需要訪問私人文件所以我創建了一個內容提供者。我只是改變了中openFile方法:

@Override 
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { 
    File privateFile = new File(getContext().getCacheDir(), uri.getPath()); 
    return ParcelFileDescriptor.open(privateFile, ParcelFileDescriptor.MODE_READ_ONLY); 
} 

清單:

<provider 
     android:name=".ShareContentProvider" 
     android:authorities="com.package.example" 
     android:grantUriPermissions="true" 
     android:exported="true"> 
    </provider> 

當打開郵件應用程序分享它說的文件,它不能附加的文件,因爲它只有0字節。通過藍牙共享也失敗了。但是我可以在Content Provider中讀出privateFile,所以它存在並且它有內容。問題是什麼?

+0

是在您的自定義ContentProvider中調用的query()方法嗎? – pskink

+0

在openFile之前調用3次。第一個參數總是:content://com.package.example/file.txt – L3n95

+2

而投影/列是:_display_name和_size?順便說一句,爲什麼不使用'android.support.v4.content.FileProvider'? – pskink

回答

4

感謝pskink。 FileProvider完美工作:

搖籃依賴性:

compile 'com.android.support:support-v4:25.0.0'

清單:

<provider 
     android:name="android.support.v4.content.FileProvider" 
     android:authorities="com.package.example" 
     android:exported="false" 
     android:grantUriPermissions="true"> 
     <meta-data 
      android:name="android.support.FILE_PROVIDER_PATHS" 
      android:resource="@xml/file_paths" /> 
    </provider> 

在XML文件夾file_paths.xml:

<?xml version="1.0" encoding="utf-8"?> 
<paths xmlns:android="http://schemas.android.com/apk/res/android"> 
    <cache-path name="cache" path="/" /> 
</paths> 

共享意圖:

File file = new File(context.getCacheDir(), filename); 

    Uri contentUri = FileProvider.getUriForFile(context, "com.package.example", file); 

    Intent shareIntent = new Intent(Intent.ACTION_SEND); 
    shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri); 
    shareIntent.setType("text/plain"); 
    context.startActivity(Intent.createChooser(shareIntent, context.getResources().getText(R.string.chooser))); 
+0

您可能還需要將其添加到意圖中: shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); –