启用StrictMode时,它总是抱怨FileReader具有DiskReadViolation。无论我如何改进,它仍然存在。我怀疑它与UIThread滞后问题有关,请告诉我如何修复它,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;
}
编辑: getCpuFreq()放在asynctask中,但是onpostexcute()的位置错误。 @rciovati,感谢您的提醒,并在答案中发布您的文字,以便我接受。
答案 0 :(得分:1)
考虑使用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
}
}
}
答案 1 :(得分:0)
这是一个RxJava版本:
public Observable<Float> getFreq() {
return Observable
.create(subscriber -> {
try {
float result = -1;
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
br = new BufferedReader(fr);
result = Float.parseFloat(br.readLine().trim());
result = result / 1000;
} finally {
if (fr != null) {
fr.close();
}
if (br != null) {
br.close();
}
}
subscriber.onNext(result);
subscriber.onCompleted();
} catch (IOException e) {
subscriber.onError(e);
}
})
.cast(Float.class)
.subscribeOn(Schedulers.io());
}
以下是如何使用它:
getFreq()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(freq -> {
App.L.debug(freq.toString());
}, error -> {
App.L.error(error.toString());
});