简体   繁体   English

Android棉花糖在SD卡上写公共文件

[英]android marshmallow writing public file on sdcard

I want to save some file in a subfolder of SDCard Documents folder. 我想将一些文件保存在SDCard Documents文件夹的子文件夹中。 I've read many posts, finally I don't have any exception, it seems the file store is fine, but i still cannot see the folder, nor the files, when i connect the phone to the comp. 我看过很多帖子,最后我没有任何异常,似乎文件存储很好,但是当我将手机连接到comp时,我仍然看不到文件夹或文件。

EDIT 编辑

this occurs only on the device, on emulator, the file is created 这仅在设备上,在模拟器上创建文件时发生

I've granted permission in manifest file 我已在清单文件中授予权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

I've asked for write permission from the user, and it is granted. 我已经要求用户提供写许可,并且它被授予。 This post This post helped me in granting permission 这篇文章这篇文章帮助我授予了权限

here is my code 这是我的代码

    if (!Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
        Toast.makeText(_ctx, "There is no external storage", Toast.LENGTH_LONG).show();
    } else {
        File docfolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
        docfolder.mkdirs();
        if (!docfolder.exists()) {
            Toast.makeText(_ctx, "Documents doesn't exist", Toast.LENGTH_LONG).show();
        }
        File folder = new File(docfolder, foldername);
        folder.mkdirs(); //make if not exist

        boolean isPresent = folder.exists();
        if (isPresent) {
            File file = new File(folder.getAbsolutePath(), filename);

            try {
                OutputStream os = new FileOutputStream(file);
                os.write(xml.getBytes());
                os.close();
            } catch (IOException e) {
                Toast.makeText(_ctx, e.toString(), Toast.LENGTH_LONG).show();

                Log.w("ExternalStorage", "Error writing " + file, e);
            }
            catch (Exception e) {
                Toast.makeText(_ctx, e.toString(), Toast.LENGTH_LONG).show();

                Log.w("ExternalStorage", "Error writing 2 " + file, e);
            }
        } else {
            Toast.makeText(_ctx, "cannot make directory " + foldername, Toast.LENGTH_LONG).show();
            Log.w("ExternalStorage", "cannot make directory " + foldername);
        }

any hint is welcomed! 任何提示都欢迎!

EDIT 编辑

maybe the issue could be that this code saves file into that path? 也许问题在于此代码会将文件保存到该路径中?

/storage/emulated/0/Documents/IBHTrack/ibhTrack_GPX_20170706153858.xml /storage/emulated/0/Documents/IBHTrack/ibhTrack_GPX_20170706153858.xml

however since i use the Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) method, i don't know how to get the real SDCard path 但是,由于我使用Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)方法,所以我不知道如何获取真实的SDCard路径

Firstly check permissions: 首先检查权限:

 void checkPermission(Activity thisActivity){
        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                Toast.makeText(MainActivity.this,"Permission denied, now log will not write in storage.",Toast.LENGTH_SHORT).show();

            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(thisActivity,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        101);

            }
        }else {
                processFileLog(messageForLog);

        }
    }

Then Handle response of permission: 然后处理许可的响应:

@Override
    public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 101: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    processFileLog(messageForLog);
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(MainActivity.this,"Permission denied, now log will not write in storage.",Toast.LENGTH_SHORT).show();

                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

With this method you can log your data into file: 使用这种方法,您可以将数据记录到文件中:

 /**
     * Tag value
     */
    private static final String mTag = "Logs";

    /**
     * File
     */
    private static File mLogFolder = null;

    private static void writeLog() {
        if (isExternalStorageWritable()) {
            mLogFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
                    "/app-client-logs");
            if (!mLogFolder.exists()) {
                if (!mLogFolder.mkdirs()) {
                    System.out.println("Unable to create the log folder");
                }
            }
        } else {
            System.out.println("SD Card not available for read and write");
        }
    }

    public static void processFileLog(final String message) {
        writeLog();
        File file = new File(mLogFolder, mTag + ".log");
        try {
            BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
            String currentDateTimeString = DateFormat.getDateTimeInstance().format(System.currentTimeMillis());
            buf.append("\nSafety Net Request "+currentDateTimeString).append(":\n").append(message);
            buf.newLine();
            buf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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