Sharing a file from Android to Gmail or to Dropbox
- by Calaf
To share a simple text file, I started by copying verbatim from FileProvider's manual page:
<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"
...
Then I saved a text file and used, again nearly verbatim, the code under Sending binary content. (Notice that this applies more accurately in this case than "Sending text content" since we are sending a file, which happens to be a text file, rather than just a string of text.)
For the convenience of duplication on your side, and since the code is in any case so brief, I'm including it here in full.
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();
}
}
Aside from adding a value for send_to in res/values/strings.xml, the only other change I did to the generic Hello, World that Eclipse creates is to add the following in res/xml/my_paths.xml (as described on
the page previously referenced.
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<Files-path name="files" path="." />
</paths>
This code runs fine. It shows a list of intent recipients. But sending the text file to either Dropbox or to Gmail fails.
Dropbox sends the notification "Uploading to Dropbox" followed by "Upload failed: my_file.txt". After "sending message.." Gmail sends "Couldn't send attachment".
What is wrong?