API 29中的AndroidStudio getExternalStoragePublicDirectory

时间:2019-11-11 01:33:40

标签: java android

在API 29中,不赞成使用getExternalStoragePublicDirectory,因此我必须设法将以下代码转换为API 29

String pathSave = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                            + new StringBuilder("/GroupProjectRecord_")
                            .append(new SimpleDateFormat("dd-MM-yyyy-hh_mm_ss")
                            .format(new Date())).append(".3gp").toString(); 

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

如android docs

中所述
  

应用程序可以继续访问共享/外部存储中存储的内容   通过迁移到诸如   Context#getExternalFilesDir(String)

尝试这种方法。

public void getFilePath(Context context){
        String path = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
                + new StringBuilder("/GroupProjectRecord_")
                .append(new SimpleDateFormat("dd-MM-yyyy-hh_mm_ss")
                        .format(new Date())).append(".3gp").toString();

        Log.d(TAG, "getFilePath: "+path);
    }

答案 1 :(得分:0)

在API 29及更高版本中,使用应用程序私有存储之外的路径执行任何操作均不起作用。

有关详情,请参见https://developer.android.com/training/data-storage/files/external-scoped

因此,要保存,您需要执行以下操作:-


    // OnClick Save Button
    public void Save(View view){

        // Ask for a new filename
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        // Restrict to openable items
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        // Set mimeType
        intent.setType("text/plain");
        // Suggest a filename
        intent.putExtra(Intent.EXTRA_TITLE, "text.txt");
        // Start SAF file chooser
        startActivityForResult(intent, 1);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
        super.onActivityResult(requestCode, resultCode, resultData);

        if (requestCode == 1 && resultCode == RESULT_OK) {
            Log.d("SAF", "Result code 1");
            if (resultData != null) {
                Uri uri = resultData.getData();
                Log.d("SAF", uri.toString());

                // Now write the file
                try {
                    ParcelFileDescriptor pfd =
                            this.getContentResolver().
                                    openFileDescriptor(uri, "w");

                    // Get a Java FileDescriptor to pass to Java IO operations
                    FileDescriptor fileDescriptor = pfd.getFileDescriptor();

                    // Read Input stream
                    FileOutputStream fileOutputStream =
                            new FileOutputStream(fileDescriptor);

                    // .....

                } catch (Exception e){
                    // Do something with Exceptions
                }
            } else {
                Log.d("SAF", "No Result");
            }
        }
    }