顏子鈞
顏子鈞

Reputation: 21

android 8.0+ How to rw in sdcard

  1. I use system permission.And I announced permission to read and write in sdcard. According to the past, the following writing methods were made. But in Android 8.0+ devices. I always get permission denied at logFile.createNewFile(). But if my file path replace to internal storage is pass.

  2. Looking for the network data, only find a SAF mechanism may provide assistance, but this mechanism is the file manager of the intent machine itself, after returning a URI to perform the function of reading and writing files, the same URI is given to the same funtion Unable to create a new file successfully.(https://github.com/termux/termux-app/issues/812)

  3. I try to use execute function Runtime.getRuntime().exec("push '/storage/emulated/0/eee.txt' '/storage/3630-6236/'"). But it doesn't work,either.

Is there any solutions to write on Android 8.0+ sdcard?Currently trying to use DocumentFile to do.(https://github.com/TeamAmaze/AmazeFileManager/blob/master/app/src/main/java/com/amaze/filemanager/filesystem/HybridFile.java)

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

Upvotes: 0

Views: 1840

Answers (2)

Christos Themelis
Christos Themelis

Reputation: 189

At Android 8+ you have to add also the READ_EXTRERNAL_STORAGE permission

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

Upvotes: 0

WildWind
WildWind

Reputation: 162

1 Only define permissions in AndroidManifest.xml is not enough, you have to requestPermissions in onCreate @MainActivity. 2 Another way to solve it is to target the sdk version to lower than M, for ex targetSdkVersion 15.

Upvotes: 1

Related Questions