android 8.0+如何在SD卡中使用

问题描述 投票:0回答:2
  1. 我使用系统权限。我宣布允许读取和写入SD卡。根据过去,制作了以下书写方法。但在Android 8.0+设备中。我总是在logFile.createNewFile()中获得权限被拒绝。但如果我的文件路径替换为内部存储是通过。
  2. 寻找网络数据,只找到一个SAF机制可能会提供帮助,但是这个机制是意图机器本身的文件管理器,在返回一个URI来执行读写文件的功能之后,同样的URI被赋予相同的URI功能无法成功创建新文件。(https://github.com/termux/termux-app/issues/812
  3. 我尝试使用执行函数Runtime.getRuntime()。exec(“push'/ storage_emulated/0/eee.txt''/ storage / 3630-6236 /'”)。但它也不起作用。

有没有在Android 8.0+ sdcard上编写的解决方案?目前正在尝试使用DocumentFile。(https://github.com/TeamAmaze/AmazeFileManager/blob/master/app/src/main/java/com/amaze/filemanager/filesystem/HybridFile.java

  1. 我的程式使用的是系统权限,也确实有宣告读与写的权限。在过去的Android 版本中,此段程式码都是不会出错的,但是最近在撰写Android 8.0+ 以上的版本时,logFile.createNewFile()却出现了permission denied。
  2. 查找了网路资料,只找到一篇SAF机制也许可以提供协助,但是这个机制是intent机器本身的档案总管,回传一个URI后执行读写档案的功能,以同样的URI给了同样的funtion却无法成功建立新档案。
  3. 我也利用了execute方式,以push的方式尝试,但还是没有效果,依然是IOException.

请问大家还有什么方式能在Android 8.0+ sdcard上面做写入的动作吗?

 private final static String localFullPath = PATH_SDCARD + File.separator + nowFormat + "_log.txt";

 public static void logWriter(String logText) {
        try {
            File logFile = new File(localFullPath);
            if (!logFile.exists()) {
                if (logFile.createNewFile()) {
                    Log.d("mkdir", "Create new file: " + localFullPath);
                }
            }

            Date date = new Date(System.currentTimeMillis());
            final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault());
            String nowFormat = simpleDateFormat.format(date);

            FileWriter fileWriter = new FileWriter(localFullPath, true);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.append("[").append(nowFormat).append("] ").append(logText);
            bufferedWriter.newLine();
            bufferedWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

  private void CheckPermission() {
//        CheckStoragePermission();
        String PERMISSION_WRITE_STORAGE = "android.permission.WRITE_EXTERNAL_STORAGE";
        String PERMISSION_READ_PHONE_STATE = "android.permission.READ_PHONE_STATE";
        String PERMISSION_ACCESS_FINE_LOCATION = "android.permission.ACCESS_FINE_LOCATION";
        String PERMISSION_ACCESS_COARSE_LOCATION = "android.permission.ACCESS_COARSE_LOCATION";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if ((ContextCompat.checkSelfPermission(this, PERMISSION_WRITE_STORAGE) != PackageManager.PERMISSION_GRANTED) ||
                    (ContextCompat.checkSelfPermission(this, PERMISSION_ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) ||
                    (ContextCompat.checkSelfPermission(this, PERMISSION_ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) ||
                    (ContextCompat.checkSelfPermission(this, PERMISSION_READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)) {
                String[] perms = {PERMISSION_WRITE_STORAGE, PERMISSION_READ_PHONE_STATE, PERMISSION_ACCESS_FINE_LOCATION, PERMISSION_ACCESS_COARSE_LOCATION};
                int permsRequestCode = 1;
                requestPermissions(perms, permsRequestCode);
            }
        }
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
    }



 public static String[] getExtSdCardPathsForActivity(Context context) {
        List <String> paths = new ArrayList <>();
        for (File file : context.getExternalFilesDirs("external")) {
            if (file != null) {
                int index = file.getAbsolutePath().lastIndexOf("/Android/data");
                if (index < 0) {
                    Log.w(LOG, "Unexpected external file dir: " + file.getAbsolutePath());
                } else {
                    String path = file.getAbsolutePath().substring(0, index);
                    try {
                        path = new File(path).getCanonicalPath();
                    } catch (IOException e) {
                        // Keep non-canonical path.
                    }
                    paths.add(path);
                }
            }
        }
        if (paths.isEmpty()) paths.add("/storage/sdcard1");
        return paths.toArray(new String[0]);
    }
java android
2个回答
0
投票

1仅在AndroidManifest.xml中定义权限是不够的,您必须在onCreate @MainActivity中requestPermissions。 2另一种解决方法是将sdk版本定位到低于M,对于ex targetSdkVersion 15。


0
投票

在Android 8+,您还必须添加READ_EXTRERNAL_STORAGE权限

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        if ((checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) ||
                (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {

            Log.e(getClass().getSimpleName(), "missing permission: external storage");

            AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom));
            builder.setTitle(getResources().getString(R.string.assign_permissions));
            builder.setMessage(getResources().getString(R.string.permissions_prompt));
            builder.setPositiveButton(getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                        requestPermissions(new String[]
                                {android.Manifest.permission.READ_EXTERNAL_STORAGE,
                                android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE);
                    }
                    dialog.dismiss();
                }
            });
            builder.show();
            return;
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.