Android high CPU usage

2.8k Views Asked by At

So, I have one problem, which I can't solve. My app used over 45% of cpu samsung SII. I think the main reason is postDelayed. Here is part of my code:

           Handler a=new Handler(); 
           a.post(new Runnable(){

        @Override
        public void run() {    
        Calendar cal = Calendar.getInstance(Locale.US); 
        cal.setTime(curr); 
        Format formatter = new SimpleDateFormat("\r EE \n d");
        int currentDOW = cal.get(Calendar.DAY_OF_WEEK);
        cal.add(Calendar.DAY_OF_YEAR,(currentDOW*-1)+i+2);
        den.setText(formatter.format(cal.getTime()));  
        }
            a.postDelayed(this,400); 
        });

So, this is part of my code, it is work, but I think, it is the main reason of high CPU usage. Please help me! Thank you!

2

There are 2 best solutions below

9
On

you could optimize the code a bit , but i suspect that you simply don't stop the updating when you don't need to , so more and more updates are being accumulated .

as an example , if you change the orientation , it will add more events of the previous activitiy (which was destroyed) and you end up with double the rate of updating .

0
On

I had this problem. My app was using around 60% CPU time until I added the following code to my run() method in my worker thread:

@Override
public void run()
{
    while( _running )
    {
        // do usual stuff
        // ...

        // ** add the following to the end of your loop **

        try
        {
            Thread.sleep( 5 );
        }
        catch( InterruptedException e )
        {
            _running = false;
            /* at least we tried */
        }
    }
}

It now uses ~8% CPU with no noticeable difference.

Experiment with the value '5'. I've added an app setting to allow the user to balance better graphics (i.e. number lower than 5) with better battery usage (number higher than 5).