0

I dont understand

I have a background thread which gets cpu load and then set it to text view

Problem is when setText() method is executed UI freezes for a second, i can feel it when scrolling through other elements of 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+"%");
}

I tried a lot of stuff and eventually figure out that problem is in setText() because when i comment it UI is smooth

pedja
  • 3,285
  • 5
  • 36
  • 48

1 Answers1

1

Checkout in which thread do you create a Handler. You should do it on main (UI) thread .

Korniltsev Anatoly
  • 3,676
  • 2
  • 26
  • 37