这个问题包含几个子问题。我正在分叉这些,从this question开始。我最终会通过删除这个问题来清理。Hello-World的FileProvider
下面的程序理论上会共享一个hello-world文本文件。该代码运行,但共享到Dropbox或Gmail(仅通过两个具体示例)失败。
public class MainActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String filename = "hellow.txt";
String fileContents = "Hello, World!\n";
byte[] bytes = fileContents.getBytes();
FileOutputStream fos = null;
try {
fos = this.openFileOutput(filename, MODE_PRIVATE);
fos.write(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
File file = new File(filename);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
shareIntent.setType("application/txt");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));
file.delete();
}
}
除了在res /价值/ strings.xml中添加值send_to
,只有另一对我没有到Eclipse将创建通用Hello, World
的变化是增加了以下<provider>
标签在AndroidManifest.xml:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mycorp.helloworldtxtfileprovider.MainActivity"
android:exported="false"
android:grantUriPermissions="true" >
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/my_paths" />
</provider>
<activity
android:name="com.mycorp.helloworldtxtfileprovider.MainActivity"
...
...并增加在res以下/ XML/my_paths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="files" path="." />
</paths>
我的主要问题是杉木st,但是当你在这个话题上时,关于问题2-4的讨论也会很有趣。
- 为什么上面的程序失败?
- 确实如此,如果需要自定义
ContentProvider
,那么需要扩展该类,但如果只需要一个FileProvider
,那么可以使用该类而不派生? - 在此代码中,我需要使用
filename
两次,一次使用openFileOutput
,另一次使用。有没有办法避免这种重复(这将保证相同的文件被引用)? - 在调用
startActivity(..)
之后立即删除文件是否安全,还是有必要设计一个回调来等待学习文件已上传/共享。 (真正的文件可能需要一些时间来分享/上传。)
编辑
的代码运行正常,并显示应用程序发送到列表。
如果我选择Dropbox,我可以选择位置很好。 Dropbox发送通知“上传到Dropbox”,然后发送“上传失败:my_file.txt”。
如果我选择Gmail,我可以填充收件人并显示文件附加,但在“发送邮件..”后,我收到“无法发送附件”。
我们希望您不要通过并删除其他人花时间回答的问题。问题不仅仅是为了你的利益,而且对于未来很多人可能正在寻找类似的东西。 –
@BradLarson我打破了一个问题/一个职位的规则,并付出了代价。我这样做使得它对于一些善良的灵魂敞开心扉,就像那些回答在不重要问题的答案中给予明智的答案,而没有解决问题的症结(第1部分)的人一样。正如我在评论中提到的那样,我将把问题分解成几个子部分。我尝试了一个重点放在第1部分的问题。没有人提出答案。我宁愿删除它。最终,由于提出这个问题,我意识到问题更复杂,例如用户处于飞行模式时。 TBC。 – Calaf