什么是Android中的严格模式政策违规

时间:2019-11-27 00:38:54

标签: android-permissions disk strict-mode

public static void write(byte [] aInput,String aOutputFileName,String dirName){

    (new File(dirName)).mkdir();
    try {
        OutputStream output = null;
        try {
            output = new BufferedOutputStream(new FileOutputStream(dirName + "/" + aOutputFileName));
            output.write(aInput);
        } finally {
            output.close();
        }
    } catch (FileNotFoundException ex) {
        System.out.println("File not found.");
    } catch (IOException ex) {
        System.out.println(ex);
    }
}

上面的代码来自我正在使用的库,应该创建一个输出文件并向其中写入一个字节数组。我检查了logcat并看到严格模式策略违反Write.toDisk。我了解我的问题应该是:(1)严格模式是否会阻止您在主线程上进行磁盘读写? (2)这是否意味着未实际创建文件或文件夹? (3)那我该如何在我的应用程序内创建一个不会触发此操作的文件夹或文件? (4)处理磁盘读写主ui线程的推荐方法是什么,不妨举一个真实的例子

预先感谢

1 个答案:

答案 0 :(得分:0)

(1) It turns out that Strict mode doesn't actually prevent you from making writes to the disk it just gives a warning. From Android Developer "StrictMode is a developer tool which detects things you might be doing by accident and brings them to your attention so you can fix them". https://developer.android.com/reference/android/os/StrictMode
(2) The files were actually being created it's just that I was just not familiar with writing and reading from disk
(3) There are numerous ways to go about creating files (i) first you get a hold of a file directory to write the file to: 
context.getFilesDir()
(ii) then you get an outputstream writer (iii) then you write out the data with the writer
 public void makeFile(String filename){
        //Create temp file for filename
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(new File(filename));
            fos.write(filename.getBytes());//Write the contents of the file to app folder
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
(iv) finally you close the outputstream writer
(4) The recommended way is to use either an AsyncTask or some other background running class like FutureTask or to use Threads or Runnable:
public class DownloadFileThread implements Runnable{
      public void run(){
          //your code here
     }
}