写入文件(内部存储)并通过mail / bluetooth.as .txt文件共享

时间:2016-12-25 13:23:42

标签: android email file-transfer

我今天才开始使用Android(所以我对此感到陌生)并且我试图实现这一目标:

让用户输入一些数据。将此数据另存为.txt文件。 (在Internal Storage,因为我的目标手机没有SD卡)。阅读此.txt文件并通过邮件将其作为附件共享或通过任何其他方式共享。 (Bluetooth/Whatsapp/Facebook/Drive)等。

问题在于:

我可以让用户保存数据。我也能读回来。但是,当我尝试分享它时,它就像纯文本一样。即,如果我通过GMail分享它,它不会作为文本文件附件,而是文本本身作为邮件正文。通过bluetooth分享它会使它成为.html文件,如果可以通过邮件发送,它仍然可以解决我的目的。

我的代码:

将数据(以字节流形式)保存到文件:

@Override
public void onReceivedData(byte[] arg0) {
    data = new String(arg0, "UTF-8");
    String filename = "testFile.txt";
    FileOutputStream outputStream;
    try {
        outputStream = openFileOutput(filename, Context.MODE_APPEND);
        outputStream.write(data.getBytes());
        //The following 2 lines just for feedback
        data = data.concat(" Wrote to file");
        tvAppend(textView, data);
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

从文件中读取并作为附件发送:

方法1(产生明文):

    char c;
    int i;
    String dataToSend = "";
    String filename = "testFile.txt";
    FileInputStream inputStream;
    try {
        inputStream = openFileInput(filename);
        while((i=inputStream.read())!=-1)
        {
            c=(char)i;
            dataToSend += c;
        }
        inputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    sendIntent.putExtra(Intent.EXTRA_TEXT, dataToSend);
    sendIntent.setType("text/plain");
    startActivity(sendIntent);

方法2(无效):

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
try{
    String filePath = getFilesDir().getAbsolutePath();
    File file = new File(filePath, "testFile.txt");
    sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
}
catch (Exception e)
    e.printStackTrace();
}
sendIntent.setType("*/*");
startActivity(sendIntent);

在这种方法中,我获得了共享dialog框,但所有附件/ bluetooth转移都失败了。

错误讯息:

Bluetooth: Unknown File; Request can't be handled correctly

Gmail附件:

Permission denied for the attachment

任何人都可以指导我吗?我确实经历过" Note" followingjsfiddle.net/eohtwd1u以及ContentProviderFileProvider的文档页面,但无法使其生效。我试过" filepaths.xml"方法也没有用,因此不发布与该方法相关的代码。

任何帮助将不胜感激。提前致谢。

1 个答案:

答案 0 :(得分:1)

 getFilesDir() 

提供私人内存的路径。仅适用于您的应用。邮件应用程序无法访问。

请改用getExternalFilesDir()。当您使用FileOutputStream编写文件时。

在Android 7.0上,这也无效,您必须使用文件内容提供程序。

相关问题