我不明白
我有一个后台线程,它获取 cpu 负载,然后将其设置为文本视图
问题是执行 setText() 方法时 UI 冻结了一秒钟,当滚动浏览 ui 的其他元素时我能感觉到它
Runnable runnable = new Runnable() {
@Override
public void run() {
while(thread) {
try {
RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
String load = reader.readLine();
String[] toks = load.split(" ");
long idle1 = Long.parseLong(toks[5]);
long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
try {
Thread.sleep(360);
} catch (Exception e) {
}
reader.seek(0);
load = reader.readLine();
reader.close();
toks = load.split(" ");
long idle2 = Long.parseLong(toks[5]);
long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
fLoad = (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));
} catch (IOException ex) {
}
final int load =(int) (fLoad*100);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
mHandler.post(new Runnable() {
@Override
public void run() {
setCpuLoad(load);
}
});
}
}
};
new Thread(runnable).start();
}
.
private final void setCpuLoad(int load){
cpuLoad.setProgress(load);
cpuLoadTxt.setText(load+"%");
}
我尝试了很多东西,最终发现问题出在 setText() 中,因为当我评论它时 UI 很流畅