java - 如何在 Android KitKat 上创建 .txt 文件并通过电子邮件 Intent 发送该文件

标签 java android android-studio android-4.4-kitkat

所以我已经尝试了一天在 SD 卡上创建 .txt 文件,结果发现不是我的代码错误,而是 KitKat 不再允许开发人员在外部 SD 卡上存储文件;是否有解决此问题的方法,例如临时 .txt 文件,或一些新代码来创建文件然后发送它? 这是我当前的代码,不起作用

 String DataIn = PhoneNumber + "," + dataLong + "," + dataLat;
        try
        {
        File storageDirectory = new File ("/sdcard/LocationData.txt");
            storageDirectory.createNewFile();
            FileOutputStream fout = new FileOutputStream(storageDirectory);
            OutputStreamWriter myoutwriter = new OutputStreamWriter(fout);
            myoutwriter.append(DataIn);
            myoutwriter.close();Toast.makeText(getBaseContext(),"Saved", Toast.LENGTH_SHORT).show();
        }
        catch (Exception e)
        {
            Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        Intent emailintent = new Intent(Intent.ACTION_SEND);
        emailintent.setType("text/plain");
        emailintent.putExtra(Intent.EXTRA_EMAIL, new String[]{"xxxxxxxx@xxxxxxxxx.com"});
        emailintent.putExtra(Intent.EXTRA_SUBJECT, "Data");
        emailintent.putExtra(Intent.EXTRA_TEXT, "Hello World!");
        File root = Environment.getRootDirectory();
        String DataAttachment = "/sdcard/LocationData.txt";
        File filer = new File(root, DataAttachment);
        if (!filer.exists() || filer.canRead())
        {
            return;
        }
        Uri uri = Uri.fromFile(filer);
        emailintent.putExtra(Intent.EXTRA_STREAM, uri);
        startActivity(Intent.createChooser(emailintent, "Choose an Email provider"));

最佳答案

        File dirs[] = ContextCompat.getExternalFilesDirs(getApplicationContext(),null);

        String Info = "getExternalFilesDirs()\ndirs.length: " + dirs.length;
        int nr = -1;            
        while ( ++nr < dirs.length )
            Info += "\n"+  dirs[nr].getAbsolutePath();

        Toast.makeText(this, Info, Toast.LENGTH_LONG).show();

您需要/Project/libs/android-support-v4.jar 文件。

关于java - 如何在 Android KitKat 上创建 .txt 文件并通过电子邮件 Intent 发送该文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25182774/

相关文章:

java - Android Studio - onTouchEvent - 希望在 7 个 ACTION_DOWN 事件后出现一个新屏幕

android - 将旧项目迁移到Android Studio

java - 有没有办法在 HOCON 中将节点向上移动?

android - android Jetpack Compose 中的 ComponentActivity 与 AppCompatActivity

android - 如何隐藏系统栏并仅在android中的触摸屏上可见

android - XML 渲染错误 Android 预览 N

java - 字符串在匿名内部类之外变为 null

java - Equinox 中的 Sling 日志记录配置

java - 使用 JButton 关闭 JFrame

java - 无法解析方法 'isIntentAvailable(android.content.intent)'