tags:

views:

85

answers:

1

Hello !

Is there any API by which we can get CPU or Memory usage of android?

I have tried one code as below:

Please look into it and let me know if this is the correct way?

package com.infostretch.mainactivity;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;


public class CPULoad 
{
    long total = 0;
    long idle = 0;


float usage = 0;

public CPULoad( )
{
    readUsage( );
}

public float getUsage( )
{
    readUsage( );
    return usage;
}

private void readUsage( )
{
    try
    {
        BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream( "/proc/stat" ) ), 1000 );
        String load = reader.readLine();
        reader.close();     

        String[] toks = load.split(" ");

        long currTotal = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]);
        long currIdle = Long.parseLong(toks[5]);

        this.usage = (currTotal - total) * 100.0f / (currTotal - total + currIdle - idle);
        this.total = currTotal;
        this.idle = currIdle;
    }
    catch( IOException ex )
    {
        ex.printStackTrace();           
    }
}
}

I will be very thankful for your anykind of help.

A: 

Check the Debug class. http://developer.android.com/reference/android/os/Debug.html i.e. Debug.getNativeHeapAllocatedSize()

It has methods to get the used native heap, which is i.e. used by external bitmaps in your app. For the heap that the app is using internally, you can see that in the DDMS tool that comes with the Android SDK and is also available via Eclipse.

The native heap + the heap as indicated in the DDMS make up the total heap that your app is allocating.

For CPU usage I'm not sure if there's anything available via API/SDK.

Mathias Lin
Also see http://developer.android.com/intl/de/reference/android/os/Debug.html#getMemoryInfo(android.os.Debug.MemoryInfo)
Mathias Lin
Hey Mathias..Thanks for your input but I found that the code works very fine. I was out side and so couldn't respond you.Bye the way, Right now I am working on Memory usage point. I will post it code in a day or two.
Badal
Hi Mathias.. I want to find the current memory usage in mobile through my application code, and hence DDMS can't help in this scenario. SO what I have done is I have used /proc/meminfo command and parsed the response. but it shows very less free memory. So I am just confused about response.please check my query herehttp://stackoverflow.com/questions/3170691/how-to-get-current-memory-usage-in-android
Badal