簡體   English   中英

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

[英]android marshmallow writing public file on sdcard

我想將一些文件保存在SDCard Documents文件夾的子文件夾中。 我看過很多帖子,最后我沒有任何異常,似乎文件存儲很好,但是當我將手機連接到comp時,我仍然看不到文件夾或文件。

編輯

這僅在設備上,在模擬器上創建文件時發生

我已在清單文件中授予權限

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

我已經要求用戶提供寫許可,並且它被授予。 這篇文章這篇文章幫助我授予了權限

這是我的代碼

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

任何提示都歡迎!

編輯

也許問題在於此代碼會將文件保存到該路徑中?

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

但是,由於我使用Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)方法,所以我不知道如何獲取真實的SDCard路徑

首先檢查權限:

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

        }
    }

然后處理許可的響應:

@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
        }
    }

使用這種方法,您可以將數據記錄到文件中:

 /**
     * 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