How to reduce App's CPU usage in Android phone?

倖福魔咒の 提交于 2020-01-03 02:14:07

问题


I developed an auto-call application. The app reads a text file that includes a phone number list and calls for a few second, ends the call and then repeats.

My problem is that the app does not send calls after 10~16 hours. I don't know the reason exactly, but I guess that the problem is the CPU usage. My app's CPU usage is almost 50%! How do I reduce CPU usage?

Here is part of source code:

if(r_count.compareTo("0")!=0) {
    while(index < repeat_count) {
        count = 1;
        time_count = 2;

        while(count < map.length) {
           performDial();   //start call
          reject();                   //end call
          finishActivity(1);
          TimeDelay("60");            // wait for 60sec
          count = count + 2;
          time_count = time_count + 2;
          onBackPressed();            // press back button for calling next number
          showCallLog();
          finishActivity(0);
       }
      index++;
}

This is the TimeDelay() method source:

public void TimeDelay(String delayTime) {

    saveTime = System.currentTimeMillis()/1000;
    currentTime = 0;
    dTime = Integer.parseInt(delayTime);

    while(currentTime - saveTime < dTime) {
        currentTime =  System.currentTimeMillis()/1000;

    }

}

TimeDelay() repeats in the while loop for a few times.


回答1:


The reason it's using 50% of your CPU is that Android apparently won't let it use 100% of the CPU, which a loop like the one in your TimeDelay() ordinarily would. (Or else you have two CPUs and it is in fact using 100% of one CPU.) What you're doing is called a busy wait and it should be obvious why continually checking a condition will use lots of CPU. So don't do that. Use Thread.sleep() instead. Your app will then use no CPU at all during the wait.

Also, for God's sake, why are you passing a string and then parseInting it, rather than just passing an Integer in the first place? :-)




回答2:


If your method take a long time to finish , especially the while loop. You should put Thread.sleep(50) inside your loop. This makes you processor be able to handle other processes.

Your CPU will be reduced. Not sure but you should try. Hope you get good result.



来源:https://stackoverflow.com/questions/6234271/how-to-reduce-apps-cpu-usage-in-android-phone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!