這個問題包含幾個子問題。我正在分叉這些,從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