【问题标题】:What is strict mode policy violation in Android什么是 Android 中的严格模式策略违规
【发布时间】:2020-03-22 11:48:16
【问题描述】:

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 并看到了 Strict Mode Policy 违反 Write.toDisk。我知道我的问题应该是什么:(1)严格模式是否会阻止您在主线程上进行磁盘读写? (2) 这是否意味着文件或文件夹实际上并未创建? (3) 那么我将如何在我的应用程序中创建一个不会触发此操作的文件夹或文件? (4) 什么是处理磁盘读/写主 ui 线程的推荐方法,一个真实世界的例子将不胜感激

提前致谢

【问题讨论】:

    标签: android-permissions disk strict-mode


    【解决方案1】:
    (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
         }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-18
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      相关资源
      最近更新 更多