Search code examples
androidfilereaderandroid-strictmode

Android StrictMode always complains about FileReader


When StrictMode is enabled, it always complains that FileReader has DiskReadViolation. No matter how I improved, it's still there. I suspect that it has something to do with UIThread lagging problem, please let me know how to fix it, thx.

06-03 15:28:19.764: D/dalvikvm(5726): GC_CONCURRENT freed 1515K, 60% free 3122K/7751K, external 4429K/4959K, paused 19ms+14ms
06-03 15:28:19.803: D/StrictMode(5726): StrictMode policy violation; ~duration=216 ms: android.os.StrictMode$StrictModeDiskReadViolation: policy=23 violation=2
06-03 15:28:19.803: D/StrictMode(5726):     at android.os.StrictMode$AndroidBlockGuardPolicy.onReadFromDisk(StrictMode.java:745)
06-03 15:28:19.803: D/StrictMode(5726):     at dalvik.system.BlockGuard$WrappedFileSystem.open(BlockGuard.java:228)
06-03 15:28:19.803: D/StrictMode(5726):     at java.io.FileInputStream.<init>(FileInputStream.java:80)
06-03 15:28:19.803: D/StrictMode(5726):     at java.io.FileInputStream.<init>(FileInputStream.java:132)
06-03 15:28:19.803: D/StrictMode(5726):     at java.io.FileReader.<init>(FileReader.java:66)
06-03 15:28:19.803: D/StrictMode(5726):     at util.CpuUtil.getCpuFreq(CpuUtil.java:30)


public static float getCpuFreq() {
    float result = -1;
    FileReader fr = null;
    BufferedReader br = null;
    try {
        fr = new FileReader("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");// (CpuUtil.java:30)
        br = new BufferedReader(fr);
        result = Float.parseFloat(br.readLine().trim());
        result = result / 1000;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fr != null) {
                fr.close();
            }

            if (br != null) {
                br.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return result;
}

EDIT: getCpuFreq() is put in asynctask, but the wrong place of onpostexcute(). @rciovati, thank you for your reminding, and plz post your words in answers so I can accept it.


Solution

  • Consider using an AsyncTask:

    public class MainActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            new YourAsyncTask().execute();
        }
    
        static class YourAsyncTask  extends AsyncTask<Void, Void, String> {
    
            @Override
            protected String doInBackground(Void... unused) {
                //Put your code inside here
            }
        }
    }