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); –