简体   繁体   中英

How to create a .txt file on Android KitKat and send it with an email intent

So i've been trying for a day now to create a .txt file on the SD card only to find out it wasnt my code that was wrong but KitKat no longer allows devs to store files on the external SD card; is there away around this such as a temporary .txt file, or some new code to create a file then send it? this is my current code that doesnt work

 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"));

i used this code to create .txt file on external storage and its working fine on all versions

 File rootPath = new File(Environment.getExternalStorageDirectory(), DNAME);
    if(!rootPath.exists()) {
        rootPath.mkdirs();
    }
    File dataFile = new File(rootPath, FILENAME);
    if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        Toast.makeText(this, "Cannot use storage.", Toast.LENGTH_SHORT).show();
        finish();
        return;
    }
    try {           
        FileOutputStream mOutput = new FileOutputStream(dataFile, false);
        String data = "DATA";
        mOutput.write(data.getBytes());
        mOutput.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
        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();

You need /Project/libs/android-support-v4.jar file.

for me following solution worked. to create a text file use this

    File root = new File(DIRECTORY_PATH);
    File gpxfile = new File(root, "samples.txt");
    FileWriter writer = new FileWriter(gpxfile);
    writer.append("First string is here to be written.");
    writer.flush();
    writer.close();

for email

    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setData(Uri.parse("mailto:"));
    shareIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "email" });
    shareIntent.putExtra(Intent.EXTRA_SUBJECT, "test " +    "Subject");
    shareIntent.putExtra(Intent.EXTRA_TEXT, "test body");
    shareIntent.setType("application/octet-stream");
            shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse("file://"+DIRECTORY_PATH+"/samples.txt"));
    startActivityForResult(Intent.createChooser(shareIntent, "Choose service"),EMAIL_ACTIVITY_REQUEST_CODE);

Hello use this method to store file in SD Card:

 public void generateNoteOnSD(String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "hChat");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

and for send this file with intent then use these LOC

** File sd = Environment.getExternalStorageDirectory();
            File fileDir= new File(sd, "dir_path");
            Intent email = new Intent(Intent.ACTION_SEND);
            email.putExtra(Intent.EXTRA_STREAM, Uri.parse(fileDir.getAbsolutePath() + "/"
                            + "hchatDB.txt"));
                    startActivity(Intent.createChooser(email , "Email: Text File"));**

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM